Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和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

就像绑定DOM元素的属性一样,小主也可以绑定组件的props。例如,我们可以绑定 <Keypad> 组件的 value prop,就像它是一个表单元素一样。 首先,我们需要将该prop标记为 可绑定 。在 Keypad.svelte 中,更新 $props() 声明以使用 $bindable 符文(rune):

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();

然后,在 App.svelte 中,添加一个bind: 指令:

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

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

现在,当用户与键盘交互时,父组件中的 pin 值会立即更新。 [!NOTE] 请谨慎使用组件绑定。如果绑定过多,特别是在没有“单一数据源”的情况下,可能会难以跟踪应用程序中数据的流动。

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} />