Vue 3 Composition API
The Composition API is a new way to write components in Vue 3. Instead of defining data, methods, and computed separately (like in the Options API), you group related logic inside a single setup() function.
Options API vs Composition API
| Feature | Options API | Composition API |
|---|---|---|
| Where logic lives | Spread across data, methods, computed | All grouped inside setup() |
| Reusability | Mixins (can cause conflicts) | Composables (functions, very flexible) |
| TypeScript support | Limited | Much better (direct function usage) |
| Readability in large components | Logic is scattered in different blocks | Logic is grouped together → more maintainable |
| Vue 2 support | Default approach | Backported via plugin, native in Vue 3+ |
1. Basic Example
Let’s start with a simple counter using ref.
2. Reactive Objects
Use reactive() to create reactive state for objects and arrays.
3. Computed Properties
computed() lets you create derived state based on other data.
4. Watchers
watch() lets you react to state changes.
5. Reusable Composables
You can create custom functions (called composables) that encapsulate logic and reuse it across components.
// useCounter.js
import { ref } from 'vue';
export function useCounter() {
const count = ref(0);
const increment = () => count.value++;
const decrement = () => count.value--;
return { count, increment, decrement };
}Summary
- ref() → reactive primitives like numbers and strings
- reactive() → reactive objects and arrays
- computed() → derived state
- watch() → react to state changes
- Composables → reusable logic across components