就像你可以绑定到 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:
let { value = $bindable(''), onsubmit } = $props();
然后,在 App.svelte
中添加 bind:
指令:
¥Then, in App.svelte
, add a bind:
directive:
<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.
谨慎使用组件绑定。如果你的应用数据流太多,尤其是在没有 ‘单一事实来源’ 的情况下,则很难跟踪应用周围的数据流。
¥[!NOTE] 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’.
<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} />