response
The core of Svelte is a powerful response system that keeps the DOM in sync with the application state-for example, responding to an event.
In order to demonstrate it, we first need a program that triggers an event:
<button on:click={handleClick}>
In the handleClick function, all we need to do is to change the value of count:
function handleClick() {
count += 1;
}
Complete code:
<script>
let count = 0;
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
Response statement
When the state of the component changes, Svelte will automatically update the DOM. Usually, some parts of the component state need to be calculated from other parts (for example, fullname derived from firstname and lastname), and recalculated when they change.
For these, we declare as follows:
let count = 0;
$: doubled = count * 2;
Don't worry, this may seem a little weird, but it is valid JavaScript, which Svelte interprets as "when any referenced value changes, run this code". Once you get used to it, you can't go back.
Let's achieve the double effect in HTML:
<p>{count} doubled is {doubled}</p>
Of course, you can just write {count * 2}
in HTML without using the response. The response becomes especially valuable when you need to quote the response multiple times, or when your value depends on other responses.
Complete code:
<script>
let count = 0;
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
We are not limited to response variables-we can also run arbitrary statements in the response. For example, if the value of count changes, we can print the output:
$: console.log(`the count is ${count}`);
You can also easily combine statements into a block of code:
$: {
console.log(`the count is ${count}`);
alert(`I SAID THE COUNT IS ${count}`);
}
You can even put $:
in front of grammars like judging branches:
$: if (count >= 10) {
alert(`count is dangerously high!`);
count = 9;
}
The complete code is as follows:
<script>
let count = 0;
$: if (count >= 10) {
alert(`count is dangerously high!`);
count = 9;
}
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
Update arrays and objects
Because Svelte's response is triggered by assignment, using array methods like push and splice will not automatically cause updates.
One way to solve this problem is to add a piece of code that changes the length of the array:
function addNumber() {
numbers.push(numbers.length + 1);
numbers = numbers;
}
But there is a more concise solution:
function addNumber() {
numbers = [...numbers, numbers.length + 1];
}
You can use similar patterns to replace pop, shift, unshift, and concat.
Assignment to array and object properties-for example, obj.foo+=1
or array[i]=x--
works in the same way as the assignment to the value itself.
function addNumber() {
numbers[numbers.length] = numbers.length + 1;
}
A simple rule of thumb: the name of the updated variable must appear on the left side of the assignment. For example this:
const foo = obj.foo;
foo.bar = 'baz';
obj.foo.bar
will not be updated unless you use obj=obj
.
Complete code:
<script>
let numbers = [1, 2, 3, 4];
function addNumber() {
numbers = [...numbers, numbers.length + 1];
}
$: sum = numbers.reduce((t, n) => t + n, 0);
</script>
<p>{numbers.join(' + ')} = {sum}</p>
<button on:click={addNumber}>
Add a number
</button>
If you want to practice the above functions yourself, you can steadily experience it in the Sevlte official website tutorial: reactive
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。