Summary of several keywords in svelte

In svelte, some keywords are inconsistent with other frameworks. It will feel strange when you first get in touch, and it is difficult to remember their usage scenarios. Here I will summarize them together, hoping to compare them and make them easier to understand.

bind

When we need two-way binding, we use the bind keyword, so that our value changes and can be directly reflected on the page UI:

<script>
  let name = 'world';
</script>

<input bind:value={name}>

<h1>Hello {name}!</h1>

Bind the value of the input to the name, and when the input in the input box is updated, the value of the name will also change accordingly!

this

Binding this is similar to Vue's ref function, both to obtain the actual DOM object of the current component.

<script>
	let text;
  function clickFunc() {
    alert(text.type);
  }
	
</script>

<div>
  <input type="text" value="input value" bind:this={text} on:click={() => clickFunc()}/>
</div>

By binding this to the input dom, we can directly obtain the various attribute values ​​​​of the input in the script.

let

The slot attribute is added to the slot. If you want to expose the attribute in the parent component, you need to use the let keyword.

# Click.svelte
<script>
    let clicked;

    function clickevent() {
        clicked = true;
    }
</script>


<div on:click={clickevent}>
    <slot click={clicked}></slot>
</div>

#App.svelte
<script>
	import Click from './Click.svelte';
	
</script>

<Click let:click={clicked}>
  <span>{clicked}</span>
</Click>

Guess you like

Origin blog.csdn.net/ramblerviper/article/details/124989770
Recommended