document store bindings and $foo += 1

pull/2432/head
Rich Harris 6 years ago
parent d6d9a5ee01
commit b815ac7be9

@ -0,0 +1,6 @@
<script>
import { name, greeting } from './stores.js';
</script>
<h1>{$greeting}</h1>
<input value={$name}>

@ -0,0 +1,8 @@
import { writable, derived } from 'svelte/store';
export const name = writable('world');
export const greeting = derived(
name,
$name => `Hello ${$name}!`
);

@ -0,0 +1,10 @@
<script>
import { name, greeting } from './stores.js';
</script>
<h1>{$greeting}</h1>
<input bind:value={$name}>
<button on:click="{() => $name += '!'}">
Add exclamation mark!
</button>

@ -0,0 +1,8 @@
import { writable, derived } from 'svelte/store';
export const name = writable('world');
export const greeting = derived(
name,
$name => `Hello ${$name}!`
);

@ -0,0 +1,23 @@
---
title: Store bindings
---
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:
```html
<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:
```html
<button on:click="{() => $name += '!'}">
Add exclamation mark!
</button>
```
The `$name += '!'` assignment is equivalent to `name.set($name + '!')`.
Loading…
Cancel
Save