Svelte基础
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
小主您可能经常需要从一个状态 衍生 另一个状态,为此贴心的Svelte提供了$derived
符文(rune):
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>
使用$derived
声明的表达式只有在它的依赖状态(在这个例子中就是numbers
)更新时才会重新计算。不同于普通状态,衍生状态都是只读的。
The expression inside the
$derived
declaration will be re-evaluated whenever its dependencies (in this case, justnumbers
) are updated. Unlike normal state, derived state is read-only.
是不是跟React中的useCallback, useMemo类似啊?!小主。
previous next
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>