mirror of https://github.com/sveltejs/svelte
parent
fd2b3e4daf
commit
ffb5c16094
@ -0,0 +1,23 @@
|
||||
<script>
|
||||
import Thing from './Thing.svelte';
|
||||
|
||||
let things = [
|
||||
{ id: 1, value: 'a' },
|
||||
{ id: 2, value: 'b' },
|
||||
{ id: 3, value: 'c' },
|
||||
{ id: 4, value: 'd' },
|
||||
{ id: 5, value: 'e' }
|
||||
];
|
||||
|
||||
function handleClick() {
|
||||
things = things.slice(1);
|
||||
}
|
||||
</script>
|
||||
|
||||
<button on:click={handleClick}>
|
||||
Remove first thing
|
||||
</button>
|
||||
|
||||
{#each things as thing}
|
||||
<Thing value={thing.value}/>
|
||||
{/each}
|
@ -0,0 +1,9 @@
|
||||
<script>
|
||||
// `value` is updated whenever the prop value changes...
|
||||
export let value;
|
||||
|
||||
// ...but `valueAtStart` is fixed upon initialisation
|
||||
const valueAtStart = value;
|
||||
</script>
|
||||
|
||||
<p>{valueAtStart} / {value}</p>
|
@ -0,0 +1,23 @@
|
||||
<script>
|
||||
import Thing from './Thing.svelte';
|
||||
|
||||
let things = [
|
||||
{ id: 1, value: 'a' },
|
||||
{ id: 2, value: 'b' },
|
||||
{ id: 3, value: 'c' },
|
||||
{ id: 4, value: 'd' },
|
||||
{ id: 5, value: 'e' }
|
||||
];
|
||||
|
||||
function handleClick() {
|
||||
things = things.slice(1);
|
||||
}
|
||||
</script>
|
||||
|
||||
<button on:click={handleClick}>
|
||||
Remove first thing
|
||||
</button>
|
||||
|
||||
{#each things as thing (thing.id)}
|
||||
<Thing value={thing.value}/>
|
||||
{/each}
|
@ -0,0 +1,9 @@
|
||||
<script>
|
||||
// `value` is updated whenever the prop value changes...
|
||||
export let value;
|
||||
|
||||
// ...but `valueAtStart` is fixed upon initialisation
|
||||
const valueAtStart = value;
|
||||
</script>
|
||||
|
||||
<p>{valueAtStart} / {value}</p>
|
@ -0,0 +1,17 @@
|
||||
---
|
||||
title: Keyed each blocks
|
||||
---
|
||||
|
||||
By default, when you modify the value of an `each` block, it will add and remove items at the *end* of the block, and update any values that have changed. That might not be what you want.
|
||||
|
||||
It's easier to show why than to explain. Click the 'Remove first item' button a few times, and notice that it's removing `<Thing>` components from the end and updating the `value` for those that remain. Instead, we'd like to remove the first `<Thing>` component and leave the rest unaffected.
|
||||
|
||||
To do that, we specify a unique identifier for the `each` block:
|
||||
|
||||
```html
|
||||
{#each things as thing (thing.id)}
|
||||
<Thing value={thing.value}/>
|
||||
{/each}
|
||||
```
|
||||
|
||||
The `(thing.id)` tells Svelte how to figure out what changed.
|
Loading…
Reference in new issue