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

Events & Attributes

ใน Svelte 5 DOM event handler เป็น attribute ธรรมดา ที่ตั้งชื่อเหมือน property: onclick, oninput, onsubmit คุณส่ง function เข้าไปเหมือนที่ทำใน HTML/JS ธรรมดาเป๊ะ

<script>
let count = $state(0);
</script>
<button onclick={() => count++}>+1</button>
<input oninput={(e) => console.log(e.currentTarget.value)} />

นี่คือการเปลี่ยนที่ตั้งใจจาก Svelte 4 ซึ่งใช้ directive พิเศษ on:click ถ้าคุณอ่าน code หรือ tutorial เก่า จะเห็น on:click={handler} — เทียบเท่าแบบใหม่คือ onclick={handler} รูปแบบใหม่เป็นแค่ property จึง compose ได้เป็นธรรมชาติและ spread รวมกับ attribute อื่นได้

เมื่อ variable มีชื่อเดียวกับ attribute ให้ใช้ shorthand {value}:

<script>
let src = $state('/logo.png');
let alt = $state('Logo');
</script>
<img {src} {alt} /> <!-- shorthand for src={src} alt={alt} -->

spread object ของ attribute ทั้งก้อนด้วย {...obj} — สะดวกเวลา forward props ไปให้ element:

<script>
let { ...rest } = $props(); // collect remaining props
</script>
<button {...rest}>click</button> <!-- forward them all to the button -->

การ toggle class และ inline style แบบ reactive เกิดขึ้นบ่อยพอที่ Svelte จะให้ directive เฉพาะ

class:name={condition} เพิ่ม class เมื่อ condition เป็น truthy:

<div class:active={isActive} class:done={isDone}></div>

Svelte 5 ยังให้คุณส่ง object หรือ array ให้ attribute class ธรรมดาได้ (เหมือน helper clsx ยอดนิยม):

<div class={{ active: isActive, done: isDone }}></div>

style:prop={value} ตั้งค่า CSS property แบบ inline อย่าง reactive:

<div style:color={textColor} style:font-size="{size}px"></div>

ทั้งคู่ compile เป็นการอัปเดตที่แม่นยำ — เมื่อ isActive พลิก จะ toggle เฉพาะ class นั้น; เมื่อ textColor เปลี่ยน จะตั้งเฉพาะ style property นั้น

flowchart LR
  cls["class:active={isActive}"] --> u1["toggle exactly that class"]
  sty["style:color={textColor}"] --> u2["set exactly that CSS property"]
  ev["onclick={handler}"] --> u3["attach a plain event listener"]
directive compile เป็นการอัปเดตแบบเจาะจง
attach click handler ใน Svelte 5 อย่างไร?
event เปลี่ยนอะไรจาก Svelte 4 ไป Svelte 5?
`<img {src} {alt} />` หมายความว่าอะไร?
`class:active={isActive}` ทำอะไร?