# Vue 3 Composition API: คู่มือฉบับสมบูรณ์เพื่อเชี่ยวชาญระบบ Reactivity > เชี่ยวชาญ Vue 3 Composition API ผ่านคู่มือเชิงปฏิบัตินี้ เรียนรู้ ref, reactive, computed, watch และ composables เพื่อสร้างแอปพลิเคชัน Vue ที่มีประสิทธิภาพสูง - Published: 2026-01-07 - Updated: 2026-04-06 - Author: SharpSkill - Tags: vue 3, composition api, javascript, frontend, reactivity - Reading time: 12 min --- Vue 3 Composition API ถือเป็นการเปลี่ยนแปลงครั้งสำคัญในวิธีการจัดโครงสร้างคอมโพเนนต์ Vue แนวทางนี้จัดระเบียบโค้ดตามฟีเจอร์แทนที่จะจัดตามออปชัน ช่วยให้การนำลอจิกกลับมาใช้ซ้ำและการดูแลแอปพลิเคชันที่ซับซ้อนทำได้ง่ายขึ้น > **ความรู้พื้นฐานที่จำเป็น** > > คู่มือนี้สมมติฐานว่าท่านมีความรู้พื้นฐานเกี่ยวกับ Vue.js ตัวอย่างใช้ไวยากรณ์ ` ``` สำหรับอ็อบเจกต์ที่มีพร็อปเพอร์ตี้หลายตัวที่เกี่ยวข้องกัน `reactive` มอบไวยากรณ์ที่เป็นธรรมชาติมากขึ้นโดยไม่ต้องใช้ `.value` ```javascript // UserProfile.vue ``` กฎทั่วไปคือ: ใช้ `ref` สำหรับค่าพื้นฐาน (string, number, boolean) และ `reactive` สำหรับอ็อบเจกต์ที่มีโครงสร้าง ## พร็อปเพอร์ตี้ Computed ด้วย computed พร็อปเพอร์ตี้ computed คำนวณค่าจาก state แบบ reactive ค่าเหล่านี้จะถูกแคชไว้และคำนวณใหม่เฉพาะเมื่อ dependency เปลี่ยนแปลงเท่านั้น จึงมีประสิทธิภาพสูงมาก ```javascript // ProductList.vue ``` พร็อปเพอร์ตี้ computed ยังสามารถเขียนได้ (writable) โดยใช้ getter และ setter ซึ่งมีประโยชน์สำหรับการแปลงค่าสองทิศทาง ```javascript // FullName.vue ``` ## Watcher ด้วย watch และ watchEffect Watcher ทำหน้าที่รัน side effect เพื่อตอบสนองต่อการเปลี่ยนแปลงของข้อมูล Vue 3 มีสองแนวทาง: `watch` สำหรับการควบคุมที่แม่นยำ และ `watchEffect` สำหรับการติดตามอัตโนมัติ > **เมื่อไหร่ควรใช้ watch และเมื่อไหร่ควรใช้ watchEffect?** > > `watch` ให้การควบคุม dependency ที่แม่นยำและให้ทั้งค่าเก่าและค่าใหม่ `watchEffect` เหมาะกว่าเมื่อ dependency แบบ reactive ทั้งหมดที่ใช้ควรทริกเอฟเฟกต์ ```javascript // SearchComponent.vue ``` หากต้องการสังเกตอ็อบเจกต์หรืออาร์เรย์ที่ซ้อนกัน ตัวเลือก `deep` จำเป็นต้องใช้กับ `watch` ```javascript // DeepWatch.vue ``` ## การสร้าง Composable ที่นำกลับมาใช้ซ้ำได้ Composable คือฟังก์ชันที่ห่อหุ้มลอจิกแบบ reactive ที่นำกลับมาใช้ซ้ำได้ แนวทางนี้เป็นหนึ่งในจุดแข็งหลักของ Composition API สำหรับการแชร์โค้ดระหว่างคอมโพเนนต์ ```javascript // composables/useFetch.js import { ref, watchEffect, toValue } from 'vue' // Composable for HTTP requests // Automatically handles loading, errors, and refetching export function useFetch(url) { const data = ref(null) const error = ref(null) const isLoading = ref(false) // Reusable fetch function async function fetchData() { isLoading.value = true error.value = null try { // toValue() allows accepting a ref or a value const response = await fetch(toValue(url)) if (!response.ok) { throw new Error(`HTTP ${response.status}`) } data.value = await response.json() } catch (e) { error.value = e.message } finally { isLoading.value = false } } // watchEffect for automatic refetch if url is a ref watchEffect(() => { fetchData() }) // Expose state and methods return { data, error, isLoading, refetch: fetchData } } ``` Composable นี้สามารถนำไปใช้แบบ declarative ในคอมโพเนนต์ใดก็ได้ ```javascript // UserList.vue ``` ต่อไปนี้คือตัวอย่าง composable อีกตัวสำหรับจัดการสถานะฟอร์มพร้อม validation ```javascript // composables/useForm.js import { reactive, computed } from 'vue' // Form management composable export function useForm(initialValues, validationRules) { // Form state const form = reactive({ values: { ...initialValues }, errors: {}, touched: {} }) // Validate a specific field const validateField = (field) => { const rules = validationRules[field] if (!rules) return true for (const rule of rules) { const result = rule(form.values[field]) if (result !== true) { form.errors[field] = result return false } } form.errors[field] = null return true } // Validate entire form const validate = () => { let isValid = true for (const field in validationRules) { if (!validateField(field)) { isValid = false } } return isValid } // computed: form is valid if no errors const isValid = computed(() => { return Object.values(form.errors).every(e => !e) }) // Mark a field as touched (to display errors) const touch = (field) => { form.touched[field] = true validateField(field) } // Reset the form const reset = () => { form.values = { ...initialValues } form.errors = {} form.touched = {} } return { form, isValid, validate, validateField, touch, reset } } ``` ## การจัดการ Lifecycle Hook Composition API มอบ lifecycle hook ในรูปแบบฟังก์ชันที่เรียกใช้ภายใน setup Hook เหล่านี้ทำงานโค้ดในช่วงเวลาเฉพาะของวงจรชีวิตคอมโพเนนต์ > **การทำความสะอาดที่สำคัญ** > > ทำความสะอาด side effect (ไทเมอร์, event listener, subscription) ใน `onUnmounted` เสมอเพื่อป้องกันการรั่วไหลของหน่วยความจำ ```javascript // LifecycleDemo.vue ``` ## Template Ref และการเข้าถึง DOM Template ref ให้สิทธิ์เข้าถึงเอลิเมนต์ DOM หรือ instance ของคอมโพเนนต์ลูกโดยตรง คุณสมบัตินี้ยังคงมีประโยชน์สำหรับกรณีที่ต้องการจัดการโดยตรง ```javascript // InputFocus.vue ``` ## การสื่อสารระหว่าง Parent-Child ด้วย Props และ Emits Composition API ทำให้การประกาศ props และ event ทันสมัยยิ่งขึ้นด้วย `defineProps` และ `defineEmits` พร้อมการทำงานร่วมกับ TypeScript ที่ดีขึ้น ```javascript // ChildComponent.vue ``` ```javascript // ParentComponent.vue ``` ## Provide และ Inject สำหรับ Dependency Injection หากต้องการแชร์ข้อมูลระหว่างคอมโพเนนต์ที่อยู่ห่างไกลกันโดยไม่ต้อง prop drilling Vue 3 มอบ `provide` และ `inject` ให้ ```javascript // App.vue (or an ancestor component) ``` ```javascript // DeepNestedComponent.vue (anywhere in the tree) ``` ## สรุป Vue 3 Composition API มอบแนวทางที่ทรงพลังและยืดหยุ่นสำหรับการจัดระเบียบโค้ดแอปพลิเคชัน Vue แนวคิดหลักที่ควรจดจำ: - **ref** สำหรับค่าพื้นฐาน, **reactive** สำหรับอ็อบเจกต์ที่ซับซ้อน - **computed** สำหรับค่าที่คำนวณได้พร้อมการแคชอัตโนมัติ - **watch** และ **watchEffect** สำหรับ side effect แบบ reactive - **Composable** สำหรับแยกและนำลอจิกกลับมาใช้ซ้ำระหว่างคอมโพเนนต์ - **Lifecycle hook แบบฟังก์ชัน** (`onMounted`, `onUnmounted` เป็นต้น) - **provide/inject** สำหรับ dependency injection โดยไม่ต้อง prop drilling แนวทางนี้ช่วยให้การสร้างแอปพลิเคชันที่ดูแลง่ายและทดสอบได้สะดวก พร้อมกับการทำงานร่วมกับ TypeScript ได้อย่างยอดเยี่ยม ขั้นตอนต่อไปคือการศึกษารูปแบบขั้นสูง เช่น async composable และการใช้งานร่วมกับ Pinia สำหรับการจัดการ state ระดับโกลบอล --- Source: SharpSkill (https://sharpskill.dev), tech interview preparation for your real stack. HTML version of this page: https://sharpskill.dev/th/blog/vue-nuxt/vue-3-composition-api-complete-guide