Dark mode
Attribute Binding ใน Vue
Attribute Binding คือการผูกค่าจากตัวแปรใน Vue ไปยัง attribute ของ HTML element เช่น class, style, disabled, src, alt ฯลฯ
ตัวอย่าง Attribute Binding (สมัยใหม่)
vue
<script setup lang="ts">
import { ref } from "vue";
const isActive = ref(true);
const imgSrc = ref("https://vuejs.org/images/logo.png");
</script>
<template>
<button :class="{ active: isActive }">ปุ่ม</button>
<img :src="imgSrc" alt="Vue Logo" />
<input :disabled="!isActive" />
</template>
<style scoped>
.active {
background: #42b983;
color: white;
}
</style>
จุดเด่น
- ผูกค่าจาก state ไปยัง attribute ได้โดยตรง
- รองรับการ bind หลายชนิด เช่น class, style, boolean, string
- ใช้ร่วมกับ data binding และ event handling ได้
ข้อควรระวัง
- ค่าที่ bind ต้องเป็น reactive (ref, computed, reactive)
- ระวังการ bind ค่า null/undefined กับ attribute ที่สำคัญ
เปรียบเทียบกับ Data Binding และ Event Handling
- Attribute Binding: ผูกค่ากับ attribute ของ element (class, style, src, disabled ฯลฯ)
- Data Binding: ผูกค่ากับ value ของ input หรือแสดงผลใน template (ดูรายละเอียดในหัวข้อถัดไป)
- Event Handling: จัดการเหตุการณ์ เช่น click, input, change (ดูรายละเอียดในหัวข้อถัดไป)
สรุป: Attribute Binding คือรากฐานสำคัญของ Vue ที่ทำให้ UI เปลี่ยนแปลงตาม state ได้แบบ reactive