Skip to content

Single File Component (SFC)

SFC คืออะไร?

Single File Component (SFC) คือรูปแบบการเขียน component ที่แยกไฟล์ .vue ออกมาแต่ละ component โดยแต่ละไฟล์จะประกอบด้วย template, script, และ style อยู่ในไฟล์เดียวกันอย่างเป็นระเบียบ

โครงสร้างไฟล์ SFC ที่ทันสมัย

vue
<script setup lang="ts">
import { ref } from "vue";

defineProps<{ label: string }>();
const count = ref(0);
</script>

<template>
  <button @click="count++">
    {{ label }} ({{ count }})
  </button>
</template>

<style scoped>
button {
  padding: 0.5rem 1rem;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>

จุดเด่น:

  • ใช้ <script setup lang="ts"> สั้น กระชับ พร้อม TypeScript
  • style แยกเฉพาะ component ด้วย scoped

ข้อดี

  • แยกส่วน template, logic, style ชัดเจน อ่านง่าย ดูแลรักษาง่าย
  • รองรับ tooling สมัยใหม่ (auto import, type check, lint, hot reload)
  • เหมาะกับทุกขนาดโปรเจกต์ โดยเฉพาะโปรเจกต์จริง
  • สามารถใช้ฟีเจอร์ขั้นสูงของ Vue ได้เต็มที่ (slot, emits, props type)

ข้อจำกัด

  • ต้องตั้งไฟล์แยกสำหรับแต่ละ component
  • ต้องตั้งค่าตัว build (Vite, Webpack) ให้รองรับ .vue (แต่ปัจจุบันแทบทุก project รองรับแล้ว)

สรุป: SFC คือมาตรฐานการเขียน component ของ Vue ที่ดีที่สุดในปัจจุบัน เหมาะกับทุกขนาดโปรเจกต์ และควรเลือกใช้เป็นหลัก