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={incrementCount}>
Inside the incrementCount
function, all we need to do is change the value of count
:
ts
functionincrementCount () {count += 1;}
Svelte 'instruments' this assignment with some code that tells it the DOM will need to be updated.
App.svelte
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
›
⌄
⌄
⌄
⌄
⌄
<script>
let count = 0;
function incrementCount() {
// event handler code goes here
}
</script>
<button>
Clicked {count}
{count === 1 ? 'time' : 'times'}
</button>
<style>
button {
width:200px;
}
</style>
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
›
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
/* App.svelte generated by Svelte v4.2.19 */
import {
SvelteComponent,
append_styles,
attr,
detach,
element,
init,
insert,
noop,
safe_not_equal
} from "svelte/internal";
import "svelte/internal/disclose-version";
function add_css(target) {
append_styles(target, "svelte-19benre", "button.svelte-19benre{width:200px}");
}
function create_fragment(ctx) {
let button;
return {
c() {
button = element("button");
button.textContent = `Clicked ${count} ${count === 1 ? 'time' : 'times'}`;
attr(button, "class", "svelte-19benre");
},
m(target, anchor) {
insert(target, button, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) {
detach(button);
}
}
};
}
let count = 0;
function incrementCount() {
} // event handler code goes here
class App extends SvelteComponent {
constructor(options) {
super();
init(this, options, null, create_fragment, safe_not_equal, {}, add_css);
}
}
export default App;
result = svelte.compile(source, {
generate:
css:
});9
1
›
button.svelte-19benre{width:200px}