就像你可以绑定到 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} />