Skip to main content

我们不仅可以声明响应式 变量,还可以直接运行响应式 语句。比如说,我们可以在 count 变量变更时打印其值:

App.svelte
let count = 0;

$: console.log(`the count is ${count}`);

你也可以使用代码块来包含多条语句:

App.svelte
$: {
	console.log(`the count is ${count}`);
	console.log(`this will also be logged whenever count changes`);
}

你也可以在 if 代码块之前添加 $:

App.svelte
$: if (count >= 10) {
	alert('count is dangerously high!');
	count = 0;
}

Next: 更新数组和对象

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
	let count = 0;
 
	function handleClick() {
		count += 1;
	}
</script>
 
<button on:click={handleClick}>
	Clicked {count}
	{count === 1 ? 'time' : 'times'}
</button>
 
initialising