Vue 3's Composition API represents a paradigm shift in how we write Vue components. It provides better code organization, improved TypeScript support, and enhanced reusability.
What is the Composition API?
The Composition API is a set of function-based APIs that allow you to compose component logic. Instead of organizing code by options (data, methods, computed), you organize it by logical concerns.
Basic Example
import { ref, computed } from 'vue'
export default {
setup() {
const count = ref(0)
const doubled = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubled, increment }
}
}
Reactivity with ref and reactive
Vue 3 provides two main ways to create reactive state:
ref()- for primitive values and single referencesreactive()- for objects and arrays
Composables
One of the biggest advantages of the Composition API is the ability to extract and reuse logic across components using composables:
function useCounter() {
const count = ref(0)
const increment = () => count.value++
const decrement = () => count.value--
return { count, increment, decrement }
}
Lifecycle Hooks
Lifecycle hooks in the Composition API are prefixed with "on":
- onMounted()
- onUpdated()
- onUnmounted()
Conclusion
The Composition API makes Vue 3 more powerful and flexible. While the Options API still works, the Composition API is the recommended approach for new projects.