Svelte 的核心是一个强大的反应系统,用于使 DOM 与你的应用状态保持同步 - 例如,响应事件。
¥At the heart of Svelte is a powerful system of reactivity for keeping the DOM in sync with your application state — for example, in response to an event.
通过将值封装在 $state(...) 中使 count 声明具有响应性:
¥Make the count declaration reactive by wrapping the value with $state(...):
App
let count = $state(0);这称为符文,你可以通过它告诉 Svelte count 不是普通变量。符文看起来像函数,但它们是语言本身的一部分。
¥This is called a rune, and it’s how you tell Svelte that count isn’t an ordinary variable. Runes look like functions, but they’re not — when you use Svelte, they’re part of the language itself.
剩下的就是实现 increment:
¥All that’s left is to implement increment:
App
function increment() {
count += 1;
}1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
let count = 0;
function increment() {// TODO implement
}
</script>
<button onclick={increment}> Clicked {count} {count === 1 ? 'time' : 'times'}</button>