Skip to content

พื้นฐาน Vue Component แบบ Basic

Vue Component คืออะไร?

Component คือหน่วยย่อยของ UI ที่สามารถนำกลับมาใช้ซ้ำได้ใน Vue โดย component สามารถประกาศแบบง่าย ๆ ได้โดยตรงในไฟล์เดียวกับที่สร้าง Vue app (เช่น main.ts หรือไฟล์ script อื่น ๆ)

ตัวอย่าง Basic Component (Composition API + TypeScript)

ts
import { createApp, defineComponent, ref } from "vue";

const MyButton = defineComponent({
  name: "MyButton",
  props: {
    label: String,
  },
  setup(props) {
    const count = ref(0);
    const increment = () => count.value++;
    return () => (
      <button onClick={increment}>
        {props.label} ({count.value})
      </button>
    );
  },
});

const App = defineComponent({
  components: { MyButton },
  setup() {
    return () => (
      <div>
        <h1>Basic Component Example</h1>
        <MyButton label="Click me" />
      </div>
    );
  },
});

createApp(App).mount("#app");

หมายเหตุ:

  • ตัวอย่างนี้ใช้ JSX (หรือจะใช้ template string ก็ได้)
  • เหมาะกับ component ขนาดเล็ก/ตัวอย่าง/ทดลอง

ข้อดี

  • สั้น กระชับ เหมาะกับ component ง่าย ๆ
  • เหมาะสำหรับการทดลองหรือ demo
  • ไม่ต้องตั้งไฟล์แยก

ข้อจำกัด

  • ไม่เหมาะกับโปรเจกต์ขนาดใหญ่หรือ component ซับซ้อน
  • การจัดการ style, logic, template ไม่แยกส่วน อาจอ่านยาก
  • ไม่รองรับฟีเจอร์ SFC (เช่น scoped style, auto import, tooling)

ถ้าโปรเจกต์เริ่มใหญ่ขึ้น หรือ component ซับซ้อน ควรเปลี่ยนไปใช้ SFC (Single File Component) เพื่อโครงสร้างที่ดีกว่า อ่านต่อในหัวข้อถัดไป