就像您可以綁定到 DOM 元素的屬性一樣,您可以綁定到組件的屬性。 例如,我們可以綁定到這個 <Keypad>
組件的 value
屬性,就像它是一個表單元素一樣。
首先,我們需要將屬性標記為 *可綁定*。 在 Keypad.svelte
內,更新 $props()
宣告以使用 $bindable
rune
Keypad
let { value = $bindable(''), onsubmit } = $props();
然後,在 App.svelte
中,新增 bind:
指令
App
<Keypad bind:value={pin} {onsubmit} />
現在,當使用者與鍵盤互動時,父組件中的 pin
值會立即更新。
謹慎使用組件綁定。 如果您有太多綁定,並且沒有「單一真相來源」,則很難追蹤應用程式中資料的流動。
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} />