Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

就像你可以绑定到 DOM 元素的属性一样,你可以绑定到组件 props。例如,我们可以绑定到此 <Keypad> 组件的 value prop,就好像它是一个表单元素一样。

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

首先,我们需要将 prop 标记为可绑定。在 Keypad.svelte 中,更新 $props() 声明以使用 $bindable 符文:

¥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 的值会立即更新。

¥Now, when the user interacts with the keypad, the value of pin in the parent component is immediately updated.

谨慎使用组件绑定。如果应用中的数据流过多,尤其是在没有 ‘单一事实来源’ 的情况下,跟踪数据流可能会很困难。

上一页 下一页
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} />