Bindings
two-way binding เป็น sugar ของ value + event
หัวข้อที่มีชื่อว่า “two-way binding เป็น sugar ของ value + event”ปกติข้อมูลไหลทางเดียว: 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
Groups: bind:group
หัวข้อที่มีชื่อว่า “Groups: bind:group”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
bind:this สำหรับ reference ของ element และ component
หัวข้อที่มีชื่อว่า “bind:this สำหรับ reference ของ element และ component”เพื่อได้ 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>binding กับ component prop
หัวข้อที่มีชื่อว่า “binding กับ component prop”parent bind กับ prop ของ child component ได้เมื่อ child ประกาศ prop นั้นเป็น $bindable() (จากโมดูล reactivity) นี่สร้าง data flow สองทางข้าม component boundary
<script> let { value = $bindable() } = $props();</script><input bind:value={value} /><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 ง่าย ๆ