Reactivity
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.
To demonstrate it, we first need to wire up an event handler. Replace line 9 with this:
<button on:click={handleClick}>
Inside the handleClick
function, all we need to do is change the value of count
:
function handleClick() {
count += 1;
}
Svelte 'instruments' this assignment with some code that tells it the DOM will need to be updated.
App.svelte
xxxxxxxxxx
11
1
<script>
2
let count = 0;
3
4
function handleClick() {
5
// event handler code goes here
6
}
7
</script>
8
9
<button>
10
Clicked {count} {count === 1 ? 'time' : 'times'}
11
</button>
Console
xxxxxxxxxx
47
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
detach,
5
element,
6
init,
7
insert,
8
noop,
9
safe_not_equal
10
} from "svelte/internal";
11
12
function create_fragment(ctx) {
13
let button;
14
15
return {
16
c() {
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */