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:
$: console.log(`the count is ${count}`);
You can easily group statements together with a block:
$: {
console.log(`the count is ${count}`);
alert(`I SAID THE COUNT IS ${count}`);
}
You can even put the $:
in front of things like if
blocks:
$: if (count >= 10) {
alert(`count is dangerously high!`);
count = 9;
}
App.svelte
xxxxxxxxxx
11
1
<script>
2
let count = 0;
3
4
function handleClick() {
5
count += 1;
6
}
7
</script>
8
9
<button on:click={handleClick}>
10
Clicked {count} {count === 1 ? 'time' : 'times'}
11
</button>
Console
xxxxxxxxxx
78
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
detach,
6
element,
7
init,
8
insert,
9
listen,
10
noop,
11
safe_not_equal,
12
set_data,
13
space,
14
text
15
} from "svelte/internal";
16
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */