Because Svelte's reactivity is triggered by assignments, using array methods like push
and splice
won't automatically cause updates. For example, clicking the button doesn't do anything.
One way to fix that is to add an assignment that would otherwise be redundant:
function addNumber() {
numbers.push(numbers.length + 1);
numbers = numbers;
}
But there's a more idiomatic solution:
function addNumber() {
numbers = [...numbers, numbers.length + 1];
}
You can use similar patterns to replace pop
, shift
, unshift
and splice
.
Assignments to properties of arrays and objects — e.g. obj.foo += 1
or array[i] = x
— work the same way as assignments to the values themselves.
function addNumber() {
numbers[numbers.length] = numbers.length + 1;
}
A simple rule of thumb: the name of the updated variable must appear on the left hand side of the assignment. For example this...
const foo = obj.foo;
foo.bar = 'baz';
...won't update references to obj.foo.bar
, unless you follow it up with obj = obj
.
App.svelte
xxxxxxxxxx
15
1
<script>
2
let numbers = [1, 2, 3, 4];
3
4
function addNumber() {
5
numbers.push(numbers.length + 1);
6
}
7
8
$: sum = numbers.reduce((t, n) => t + n, 0);
9
</script>
10
11
<p>{numbers.join(' + ')} = {sum}</p>
12
13
<button on:click={addNumber}>
14
Add a number
15
</button>
Console
xxxxxxxxxx
85
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
detach,
6
element,
7
init,
8
insert,
9
listen,
10
noop,
11
safe_not_equal,
12
set_data,
13
space,
14
text
15
} from "svelte/internal";
16
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */