Skip to content

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งาน productionFlexible, type-safeโค้ดซับซ้อน, ต้องออกแบบดี

สรุป:

  • เริ่มต้นควรใช้ SFC เป็นหลัก
  • ใช้ฟีเจอร์ advanced เมื่อ component ซับซ้อนหรือสร้าง library
  • เข้าใจพื้นฐานก่อน แล้วค่อยขยับไป advanced เพื่อโค้ดที่ maintain ง่ายและคุณภาพสูง