Svelte基础
Svelte高阶
上下文API
特殊元素
接下来
SvelteKit基础
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
在上一个例子中我们看到状态对 重新赋值 做出了响应,状态也可以对 修改 做出响应,我们称之为 深度响应
As we saw in the previous exercise, state reacts to reassignments. But it also reacts to mutations — we call this deep reactivity.
接下来是一个深度响应的例子,首先定义个变量numbers并使用$state符文(rune)定义它的值为响应数组。
Make
numbersa reactive array:
App
let numbers = $state([1, 2, 3, 4]);现在我们改变下数组...
Now, when we change the array...
App
function addNumber() {
	numbers[numbers.length] = numbers.length + 1;
}你可以看到组件也更新了。更🐂X的是使用数组的push方法修改数组,响应依然有效。
...the component updates. Or better still, we can
pushto the array instead:
App
function addNumber() {
	numbers.push(numbers.length + 1);
}深度状态响应使用proxies实现.
Deep reactivity is implemented using proxies, and mutations to the proxy do not affect the original object.
previous next
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
let numbers = [1, 2, 3, 4];
	function addNumber() {// TODO implement
}
</script>
<p>{numbers.join(' + ')} = ...</p><button onclick={addNumber}>Add a number
</button>