Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

通常,你需要从其他状态派生状态。为此,我们有 $derived 符文:

¥Often, you will need to derive state from other state. For this, we have the $derived rune:

App
let numbers = $state([1, 2, 3, 4]);
let total = $derived(numbers.reduce((t, n) => t + n, 0));

我们现在可以在标记中使用它:

¥We can now use this in our markup:

App
<p>{numbers.join(' + ')} = {total}</p>

每当其依赖(在本例中仅为 numbers)更新时,$derived 声明中的表达式都会被重新评估。与正常状态不同,派生状态是只读的。

¥The expression inside the $derived declaration will be re-evaluated whenever its dependencies (in this case, just numbers) are updated. Unlike normal state, derived state is read-only.

上一页 下一页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
	let numbers = $state([1, 2, 3, 4]);
 
	function addNumber() {
		numbers.push(numbers.length + 1);
	}
</script>
 
<p>{numbers.join(' + ')} = ...</p>
 
<button onclick={addNumber}>
	Add a number
</button>