You need to pass reference data types (array
or object
) - here arrayItem
for the update to happen, since the update always points to the same reference in memory.
In your example, you are passing primitive types (number
and string
) - here x
and y
, these have new memory locations when created, so the update is not done on all locations!
item
<script>
export let arrayItem;
</script>
<div>
<input bind:value={arrayItem.x}>
<input bind:value={arrayItem.y}>
</div>
parent
<script>
import Item from "./Item.svelte"
let array = [
{
x: 1,
y: 2
}
];
function handleAdd() {
array = [...array, { x: 0, y: 0 }];
}
function handleLog() {
console.log(array);
}
</script>
<div>
{#each array as arrayItem}
<Item {arrayItem} />
{/each}
<button on:click={handleAdd}>add element to array</button>
<button on:click={handleLog}>log array</button>
</div>
repl example