Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

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.

First, we need to mark the prop as bindable. Inside Keypad.svelte, update the $props() declaration to use the $bindable rune:

Keypad
let { value = $bindable(''), onsubmit } = $props();

Then, in App.svelte, add a bind: directive:

App
<Keypad bind:value={pin} {onsubmit} />

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’.

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script>
	import Keypad from './Keypad.svelte';
 
	let pin = $state('');
 
	let view = $derived(pin
		? pin.replace(/\d(?!$)/g, '•')
		: 'enter your pin');
 
	function onsubmit() {
		alert(`submitted ${pin}`);
	}
</script>
 
<h1 style="opacity: {pin ? 1 : 0.4}">
	{view}
</h1>
 
<Keypad {onsubmit} />