Just as you can bind to properties of DOM elements, you can bind to component props. For example, we can bind to the value
prop of this <Keypad>
component as though it were a form element:
<Keypad bind:value={pin} on:submit={handleSubmit}/>
Now, when the user interacts with the keypad, the value of pin
in the parent component is immediately updated.
Use component bindings sparingly. It can be difficult to track the flow of data around your application if you have too many of them, especially if there is no 'single source of truth'.
App.svelte
Keypad.svelte
xxxxxxxxxx
14
1
<script>
2
import Keypad from './Keypad.svelte';
3
4
let pin;
5
$: view = pin ? pin.replace(/\d(?!$)/g, '•') : 'enter your pin';
6
7
function handleSubmit() {
8
alert(`submitted ${pin}`);
9
}
10
</script>
11
12
<h1 style="color: {pin ? '#333' : '#ccc'}">{view}</h1>
13
14
<Keypad on:submit={handleSubmit}/>
Console
xxxxxxxxxx
86
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
create_component,
6
destroy_component,
7
detach,
8
element,
9
init,
10
insert,
11
mount_component,
12
safe_not_equal,
13
set_data,
14
set_style,
15
space,
16
text,
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */