Vue 3 Composition API Basics
Master ref(), reactive(), and setup(). Build reactive components without Options API.
What is the Composition API?
The Composition API is a set of additive APIs in Vue 3 that allow you to organize component logic using imported functions instead of declaring options. It's more flexible, better for TypeScript, and encourages code reuse through composables.
Unlike the Options API, which organizes code by option type (data, methods, computed), the Composition API organizes by logical concerns. This makes it easier to extract and reuse logic across components.
ref() vs reactive()
ref() is for primitive values and objects. It requires .value to access the value.
const count = ref(0)
count.value++ // 1
console.log(count.value) // 1reactive() is for objects. It returns a reactive proxy, no .value needed.
const state = reactive({ count: 0 })
state.count++ // 1
console.log(state.count) // 1When to use each
- Use ref() for primitives (strings, numbers, booleans)
- Use reactive() for objects and arrays
- Use ref() when you need to replace the entire object
- Use reactive() when you need deep reactivity on nested objects
- Use ref() when you need to pass a value to another composable
setup() function
The setup() function is the entry point for Composition API. It runs before the component is created and gives you access to props, context, and reactive state.
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
return { count }
}
}Computed Properties
Computed properties are cached until their dependencies change. They're perfect for derived state.
import { ref, computed } from 'vue'
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
// In template: Watchers
Watchers let you watch reactive data sources and trigger side effects.
import { ref, watch } from 'vue'
const count = ref(0)
watch(count, (newValue, oldValue) => {
console.log(`Count changed from ${oldValue} to ${newValue}`)
})Key takeaways
- Composition API is more flexible than Options API
- ref() for primitives, reactive() for objects
- setup() is where you define reactive state
- Composables let you reuse logic across components
- Computed properties are cached and only re-evaluate when dependencies change
- Watchers are for side effects and async operations