The Composition API is one of the most significant features introduced in Vue 3. It provides a more flexible way to organize component logic and makes code more reusable and maintainable.
Why Composition API?
The Composition API solves several problems with the Options API:
- Better Logic Reuse: Easier to extract and reuse logic across components
- Better TypeScript Support: More natural TypeScript integration
- Better Code Organization: Related logic can be grouped together
- Better Tree Shaking: Unused code can be eliminated more effectively
Basic Setup
To use the Composition API, you need to import the necessary functions from Vue:
import { ref, reactive, computed, watch, onMounted } from 'vue';
Reactive References
The ref function creates a reactive reference to a value:
const count = ref(0);
const message = ref('Hello, Vue!');
Reactive Objects
For objects, use the reactive function:
const state = reactive({
count: 0,
message: 'Hello, Vue!',
});
Computed Properties
Computed properties are defined using the computed function:
const doubleCount = computed(() => count.value * 2);
Watchers
Watchers allow you to perform side effects when reactive data changes:
watch(count, (newValue, oldValue) => {
console.log(`Count changed from ${oldValue} to ${newValue}`);
});
Lifecycle Hooks
Lifecycle hooks are available as functions:
onMounted(() => {
console.log('Component mounted!');
});
Conclusion
The Composition API provides a more powerful and flexible way to write Vue components. While it might seem different at first, it offers significant benefits for complex applications and better code organization.