นี่คือสองวิธีในการเขียน Vue components Options API จัดระเบียบโค้ดตาม ประเภทของ option (data, methods, computed); Composition API จัดระเบียบโค้ดตาม ความเป็นห่วง ของตรรกะ โดยใช้ฟังก์ชันเช่น ref, และ
นี่คือสองวิธีในการเขียน Vue components Options API จัดระเบียบโค้ดตาม ประเภทของ option (data, methods, computed); Composition API จัดระเบียบโค้ดตาม ความเป็นห่วง ของตรรกะ โดยใช้ฟังก์ชันเช่น ref, และ
computedsetup<script>
export default {
data() { return { count: 0 }; },
computed: { double() { return this.count * 2; } },
methods: { increment() { this.count++; } },
mounted() { console.log("mounted"); },
};
</script>
ทุกอย่างจัดกลุ่มเข้าใน fixed buckets (data, methods, computed, lifecycle) ง่ายและค้นหาได้ แต่ตรรกะของ feature ชิ้นหนึ่งกระจายไปทั่ว buckets เหล่านั้น
<script setup>
import { ref, computed, onMounted } from "vue";
// all the logic for "counter" lives together
const count = ref(0);
const double = computed(() => count.value * 2);
function increment() { count.value++; }
onMounted(() => console.log("mounted"));
</script>
State, computed, methods และ lifecycle สำหรับความเป็นห่วงเดียว อยู่ด้วยกัน และ <script setup> ทำให้มันกระชับ (ไม่มี this ไม่มี return)
Composition API ช่วยให้คุณ สกัด และนำตรรกะที่มีสถานะมาใช้ใหม่ เป็นฟังก์ชันธรรมชาติ (composables):
// useCounter.js — reusable across any component
export function useCounter() {
const count = ref(0);
const increment = () => count.value++;
return { count, increment };
}
<script setup>
const { count, increment } = useCounter(); // reuse anywhere
</script>
สิ่งนี้แก้ปัญหาการนำตรรกะกลับมาใช้ใหม่อย่างสะอาด ซึ่งไม่สะดวกใน Options API (mixins มีการชนกันของชื่อและแหล่งที่มาที่ไม่ชัดเจน)
Options API → simpler mental model, fine for small components, familiar to beginners
Composition API → better for large components, TypeScript, and reusing logic (composables)
Composition API (พร้อม <script setup>) เป็น ตัวเลือกเริ่มต้นที่แนะนำ สำหรับโปรเจ็กต์ Vue 3 ใหม่ โดยเฉพาะอย่างยิ่งกับ TypeScript
Composition API คือคำตอบของ Vue 3 ในการจัดระเบียบและนำตรรกะ component มาใช้ใหม่
ความเข้าใจว่ามันจัดกลุ่มโค้ดตาม feature (ไม่ใช่ตามประเภทของ option) และเปิดใช้งาน composables — เมื่อเทียบกับ buckets ตาม option ของ Options API — อธิบายสไตล์ Vue สมัยใหม่ และเหตุใดองค์ประกอบที่ซับซ้อนและ codebases TypeScript ึจึงนิยมใช้
ทั้งสองได้รับการสนับสนุนอย่างเต็มที่; คุณแม้แต่สามารถผสมกันได้