Part 1 / Reactivity / Statements
We're not limited to declaring reactive values — we can also run arbitrary statements reactively. For example, we can log the value of count
whenever it changes:
App.svelte
let count = 0;
$: console.log(`the count is ${count}`);
You can easily group statements together with a block:
App.svelte
$: {
console.log(`the count is ${count}`);
console.log(`this will also be logged whenever count changes`);
}
You can even put the $:
in front of things like if
blocks:
App.svelte
$: if (count >= 10) {
alert('count is dangerously high!');
count = 0;
}
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