ข้ามไปยังเนื้อหา

Bindings

ปกติข้อมูลไหลทางเดียว: state → DOM binding เพิ่ม edge ย้อนกลับ เพื่อให้ form element เขียนกลับไปที่ state ด้วย bind:value เป็น shorthand ของ “set value ของ input จาก state นี้ และ update state นี้ตอน input”

<script>
let name = $state('');
</script>
<input bind:value={name} />
<p>Hello {name}</p>
<!-- เทียบเท่า เขียนเอง:
<input value={name} oninput={(e) => name = e.currentTarget.value} /> -->

binding sync ทั้งสองอัตโนมัติ และใช้ได้กับ element ที่เป็น input-like ทุกตัว: bind:value สำหรับ text/number/select, bind:checked สำหรับ checkbox, bind:files สำหรับ file input

radio button และ checkbox group ที่แชร์ state ก้อนเดียวใช้ bind:group — Svelte wire ทั้งชุดเข้ากับ variable ตัวเดียว

<script>
let flavor = $state('vanilla'); // radios: ค่าเดียว
let toppings = $state([]); // checkboxes: array
</script>
<label><input type="radio" bind:group={flavor} value="vanilla" /> Vanilla</label>
<label><input type="radio" bind:group={flavor} value="chocolate" /> Chocolate</label>
<label><input type="checkbox" bind:group={toppings} value="nuts" /> Nuts</label>
<label><input type="checkbox" bind:group={toppings} value="cherry" /> Cherry</label>

สำหรับ radio, flavor เก็บค่าที่เลือก; สำหรับ checkbox, toppings เป็น array ของค่าที่ check

เพื่อได้ reference ของ DOM node จริง (หรือ component instance) ใช้ bind:this ตัวแปรจะถูก set หลัง element mount — อ่านค่าใน effect หรือ event handler ไม่ใช่ตอน initial render

<script>
let canvas = $state(); // จะเก็บ DOM node
$effect(() => {
const ctx = canvas.getContext('2d'); // ปลอดภัย: run หลัง mount
ctx.fillRect(0, 0, 50, 50);
});
</script>
<canvas bind:this={canvas} width="200" height="200"></canvas>

parent bind กับ prop ของ child component ได้เมื่อ child ประกาศ prop นั้นเป็น $bindable() (จากโมดูล reactivity) นี่สร้าง data flow สองทางข้าม component boundary

Child.svelte
<script>
let { value = $bindable() } = $props();
</script>
<input bind:value={value} />
Parent.svelte
<script>
import Child from './Child.svelte';
let text = $state('hi');
</script>
<Child bind:value={text} /> <!-- text ของ parent และ value ของ child sync กัน -->

ใช้ component binding อย่างตั้งใจ — เพราะเปิดให้ child mutate state ของ parent ซึ่งทรงพลังแต่ทำให้ data flow ดูคลุมเครือถ้าใช้เยอะเกิน props-down/events-up มักชัดกว่าสำหรับอะไรที่เกินกว่า form control ง่าย ๆ

`bind:value={name}` เป็น shorthand ของอะไร?
ใช้อะไรสำหรับชุด radio button ที่แชร์ค่าที่เลือกเดียว?
reference จาก `bind:this` มีเมื่อไร?
child ต้องประกาศอะไรเพื่อให้ parent `bind:` กับ prop ของตัวเองได้?