Bindings
As a general rule, data flow in Svelte is top down — a parent component can set props on a child component, and a component can set attributes on an element, but not the other way around.
Sometimes it's useful to break that rule. Take the case of the <input>
element in this component — we could add an on:input
event handler that sets the value of name
to event.target.value
, but it's a bit... boilerplatey. It gets even worse with other form elements, as we'll see.
Instead, we can use the bind:value
directive:
<input bind:value={name}>
This means that not only will changes to the value of name
update the input value, but changes to the input value will update name
.
App.svelte
xxxxxxxxxx
7
1
<script>
2
let name = 'world';
3
</script>
4
5
<input value={name}>
6
7
<h1>Hello {name}!</h1>
Console
xxxxxxxxxx
51
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
space
11
} from "svelte/internal";
12
13
function create_fragment(ctx) {
14
let input;
15
let t0;
xxxxxxxxxx
51
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
space
11
} from "svelte/internal";
12
13
function create_fragment(ctx) {
14
let input;
15
let t0;
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */
xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */