# Vue 3 Composition API: Panduan Lengkap Menguasai Reaktivitas > Kuasai Vue 3 Composition API melalui panduan praktis ini. Pelajari ref, reactive, computed, watch, dan composables untuk membangun aplikasi Vue yang berkinerja tinggi. - 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 merupakan evolusi besar dalam cara komponen Vue disusun. Pendekatan ini mengorganisasi kode berdasarkan fitur, bukan berdasarkan opsi, sehingga memudahkan penggunaan ulang logika dan pemeliharaan aplikasi yang kompleks. > **Prasyarat** > > Panduan ini mengasumsikan pengetahuan dasar tentang Vue.js. Contoh-contoh menggunakan sintaks ` ``` Untuk objek dengan beberapa properti yang saling berkaitan, `reactive` menawarkan sintaks yang lebih natural tanpa memerlukan `.value`. ```javascript // UserProfile.vue ``` Aturan umumnya: gunakan `ref` untuk nilai primitif (string, number, boolean) dan `reactive` untuk objek terstruktur. ## Properti Computed dengan computed Properti computed menurunkan nilai dari state reaktif. Properti ini di-cache dan hanya dihitung ulang ketika dependensinya berubah, sehingga sangat efisien dari segi performa. ```javascript // ProductList.vue ``` Properti computed juga dapat ditulis (writable) dengan getter dan setter, berguna untuk transformasi dua arah. ```javascript // FullName.vue ``` ## Watcher dengan watch dan watchEffect Watcher menjalankan efek samping sebagai respons terhadap perubahan data. Vue 3 menyediakan dua pendekatan: `watch` untuk kontrol yang presisi dan `watchEffect` untuk pelacakan otomatis. > **Kapan menggunakan watch vs watchEffect?** > > `watch` memberikan kontrol presisi atas dependensi dan menyediakan nilai lama maupun baru. `watchEffect` lebih sederhana ketika semua dependensi reaktif yang digunakan harus memicu efek tersebut. ```javascript // SearchComponent.vue ``` Untuk mengamati objek atau array bertingkat, opsi `deep` diperlukan pada `watch`. ```javascript // DeepWatch.vue ``` ## Membuat Composable yang Dapat Digunakan Kembali Composable adalah fungsi yang mengenkapsulasi logika reaktif yang dapat digunakan kembali. Pendekatan ini merupakan salah satu kekuatan utama Composition API untuk berbagi kode antar komponen. ```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 ini kemudian dapat digunakan secara deklaratif di komponen mana pun. ```javascript // UserList.vue ``` Berikut contoh composable lain untuk mengelola state form beserta validasinya. ```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 } } ``` ## Pengelolaan Lifecycle Hook Composition API menyediakan lifecycle hook sebagai fungsi yang dipanggil di dalam setup. Hook-hook ini menjalankan kode pada momen tertentu dalam siklus hidup komponen. > **Pembersihan yang Penting** > > Selalu bersihkan efek samping (timer, event listener, subscription) di `onUnmounted` untuk menghindari kebocoran memori. ```javascript // LifecycleDemo.vue ``` ## Template Ref dan Akses DOM Template ref menyediakan akses langsung ke elemen DOM atau instance komponen anak. Fitur ini tetap berguna untuk kasus di mana manipulasi langsung diperlukan. ```javascript // InputFocus.vue ``` ## Komunikasi Parent-Child dengan Props dan Emits Composition API memodernisasi deklarasi props dan event dengan `defineProps` dan `defineEmits`, menawarkan integrasi TypeScript yang lebih baik. ```javascript // ChildComponent.vue ``` ```javascript // ParentComponent.vue ``` ## Provide dan Inject untuk Dependency Injection Untuk berbagi data antara komponen yang berjauhan tanpa prop drilling, Vue 3 menyediakan `provide` dan `inject`. ```javascript // App.vue (or an ancestor component) ``` ```javascript // DeepNestedComponent.vue (anywhere in the tree) ``` ## Kesimpulan Vue 3 Composition API menawarkan pendekatan yang powerful dan fleksibel untuk mengorganisasi kode aplikasi Vue. Konsep-konsep kunci yang perlu diingat: - **ref** untuk nilai primitif, **reactive** untuk objek kompleks - **computed** untuk nilai turunan dengan caching otomatis - **watch** dan **watchEffect** untuk efek samping reaktif - **Composable** untuk mengekstrak dan menggunakan ulang logika antar komponen - **Lifecycle hook fungsional** (`onMounted`, `onUnmounted`, dll.) - **provide/inject** untuk dependency injection tanpa prop drilling Pendekatan ini memudahkan pembuatan aplikasi yang mudah dipelihara dan diuji, sekaligus menawarkan integrasi TypeScript yang sangat baik. Langkah selanjutnya adalah mengeksplorasi pola lanjutan seperti async composable dan integrasi dengan Pinia untuk manajemen state global. --- Source: SharpSkill (https://sharpskill.dev), tech interview preparation for your real stack. HTML version of this page: https://sharpskill.dev/id/blog/vue-nuxt/vue-3-composition-api-complete-guide