Svelte knowledge points
Traversal in Svelte
By default, when you modify the value of a block, it adds each and removes the DOM node at the end of the block, and updates any values that have changed. This may not be what you want.
It is easier to say why than to explain. The <Thing> component sets the emoji to a constant at initialization, but the name is passed through prop.
Click the "Delete First Thing" button a few times and watch what happens:
It removes the last component.
It then updates the values in the remaining DOM nodes of name, but does not update the emoticons, since each emoji is fixed when <Thing> is created.
It then updates the values in the remaining DOM nodes of name, but does not update the emoticons, since each emoji is fixed when <Thing> is created.
Instead, we just want to remove the first <Thing> component and its DOM node without affecting the other components.
To do this, we specify a unique identifier (or "key") for each iteration of each block:
{#each things as thing (thing.id)}
<Thing name={thing.name}/>
{/each}
You can use any object as a key because Svelte is used inside the Map - in other words, you can use (thing) instead of (thing.id). However, it is generally safer to use strings or numbers because it means that identities persist even without reference equality, such as when updated with new data from an API server.
Modifiers in Svelte
<button on:click|once={()=>alert('clicked')}>
Click me
</button>
Binding class simplification in Svelte
<button
class="card {flipped ? 'flipped' : ''}"
on:click={() => flipped = !flipped}
>
But we can make it better. Adding or removing classes based on certain conditions is a common pattern in UI development, so Svelte includes a special instruction to simplify it: =>
<button
class="card"
class:flipped={flipped}
on:click={() => flipped = !flipped}
>
Typically, the name of the class is the same as the name of the value on which it depends: =>
<button
class="card"
class:flipped
on:click={() => flipped = !flipped}
>
Saturday, September 14, 2024 3:05:13 PM
posted by CFYYDS
Svelte