Dark mode
Advanced Component ใน Vue
แนวคิด Advanced Component
เมื่อคุณเริ่มสร้าง component ที่ซับซ้อนขึ้นใน Vue คุณจะได้ใช้ฟีเจอร์ขั้นสูง เช่น
- Dynamic Component (เปลี่ยน component ตาม runtime)
- Async Component (โหลด component แบบ lazy)
- Slot & Scoped Slot (ส่ง content เข้า component)
- Provide/Inject (แชร์ state ข้าม component tree)
- Typing Props & Emits (type-safe ด้วย TypeScript)
ตัวอย่างฟีเจอร์ขั้นสูงที่ใช้บ่อย
1. Dynamic Component
vue
<template>
<component :is="currentComponent" />
</template>
<script setup lang="ts">
import { ref } from "vue";
import Bar from "./Bar.vue";
import Foo from "./Foo.vue";
const currentComponent = ref<Foo | Bar>("Foo");
</script>
2. Async Component
ts
import { defineAsyncComponent } from "vue";
const AsyncView = defineAsyncComponent(() => import("./HeavyComponent.vue"));
3. Slot & Scoped Slot
vue
<template>
<BaseCard>
<template #header>
<h3>หัวข้อ</h3>
</template>
เนื้อหา
</BaseCard>
</template>
4. Provide / Inject
ts
// Provider
provide("theme", ref("dark"));
// Consumer
const theme = inject<string>("theme");
5. Typing Props & Emit
ts
const props = defineProps<{ label: string }>();
const emit = defineEmits<{ (e: "update", value: number): void }>();
ข้อดี
- เขียน component ที่ reusable, flexible, และ type-safe ได้จริง
- รองรับ pattern การออกแบบที่ซับซ้อน เช่น slot, dependency injection
- เหมาะกับโปรเจกต์ production, design system, หรือ library
ข้อควรระวัง
- โค้ดซับซ้อนขึ้น ต้องออกแบบดี ๆ
- การ debug และ maintain อาจยากขึ้นถ้าใช้ฟีเจอร์หลายอย่างร่วมกัน
ตารางเปรียบเทียบรูปแบบ Component
ประเภท | เหมาะกับ | จุดเด่น | ข้อจำกัด/ข้อควรระวัง |
---|---|---|---|
Basic Component | ตัวอย่าง/เล็ก ๆ | สั้น กระชับ | ไม่เหมาะกับงานซับซ้อน |
SFC (.vue) | ทุกขนาดโปรเจกต์ | แยกส่วน, tooling ครบ | ต้องตั้งไฟล์แยก |
Advanced Component | งาน production | Flexible, type-safe | โค้ดซับซ้อน, ต้องออกแบบดี |
สรุป:
- เริ่มต้นควรใช้ SFC เป็นหลัก
- ใช้ฟีเจอร์ advanced เมื่อ component ซับซ้อนหรือสร้าง library
- เข้าใจพื้นฐานก่อน แล้วค่อยขยับไป advanced เพื่อโค้ดที่ maintain ง่ายและคุณภาพสูง