If a store is writable — i.e. it has a set
method — you can bind to its value, just as you can bind to local component state.
In this example we have a writable store name
and a derived store greeting
. Update the <input>
element:
<input bind:value={$name}>
Changing the input value will now update name
and all its dependents.
We can also assign directly to store values inside a component. Add a <button>
element:
<button on:click="{() => $name += '!'}">
Add exclamation mark!
</button>
The $name += '!'
assignment is equivalent to name.set($name + '!')
.
App.svelte
stores.js
xxxxxxxxxx
6
1
<script>
2
import { name, greeting } from './stores.js';
3
</script>
4
5
<h1>{$greeting}</h1>
6
<input value={$name}>
Console
xxxxxxxxxx
71
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
component_subscribe,
6
detach,
7
element,
8
init,
9
insert,
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 */