Skip to content

Data Binding ใน Vue

Data Binding คือการผูกข้อมูลระหว่าง state ใน Vue กับ UI โดยอัตโนมัติ ทำให้เมื่อข้อมูลเปลี่ยน UI จะอัปเดตตามทันที (reactive)

ประเภทของ Data Binding

  • One-way Binding: ผูกค่าจาก state ไปแสดงใน template ()
  • Two-way Binding: ผูกค่าระหว่าง state กับ input โดยใช้ v-model (input เปลี่ยน state, state เปลี่ยน input)

ตัวอย่าง Data Binding (สมัยใหม่)

vue
<script setup lang="ts">
import { ref } from "vue";
const message = ref("Hello Vue!");
const name = ref("");
</script>

<template>
  <p>{{ message }}</p>
  <!-- One-way binding -->
  <input v-model="name" placeholder="กรอกชื่อของคุณ" />
  <!-- Two-way binding -->
  <p>สวัสดี {{ name }}</p>
</template>

จุดเด่น

  • UI อัปเดตอัตโนมัติเมื่อ state เปลี่ยน (reactive)
  • v-model ทำให้เขียนฟอร์มง่ายมาก
  • รองรับ TypeScript เต็มรูปแบบ

ข้อควรระวัง

  • หากใช้กับ object/array ซับซ้อน ต้องระวัง mutation
  • ไม่ควรใช้ two-way binding กับ prop โดยตรง (ควรใช้ emit)

เปรียบเทียบกับ Attribute Binding และ Event Handling

  • Data Binding: ผูกค่ากับ value ของ input หรือแสดงผลใน template
  • Attribute Binding: ผูกค่ากับ attribute ของ element (class, style, src ฯลฯ)
  • Event Handling: จัดการเหตุการณ์ เช่น click, input, change

สรุป: Data Binding คือหัวใจของ Vue ที่ทำให้ UI sync กับข้อมูลแบบอัตโนมัติและ reactive