Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
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 numbers a 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 push to 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.

Edit this page on GitHub

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>