Vue 3 Composition API Deep Dive
Understand the Vue 3 Composition API, including reactive state, computed properties, watchers, and composable patterns for clean, maintainable code.
FrontendIntermediate16 min read
AI Summary
Quick context for Vue 3 Composition API Deep Dive
Vue 3 Composition API Deep Dive is a intermediate guide in Frontend. Understand the Vue 3 Composition API, including reactive state, computed properties, watchers, and composable patterns for clean, maintainable code.. Key topics: composition-api, javascript, reactive, vue3.
## Why the Composition API?
Vue 3 introduced the Composition API as an alternative to the Options API. While the Options API organizes code by option type (data, methods, computed, watch), the Composition API organizes code by logical concern. This makes it easier to extract and reuse logic across components.
For complex components with many related pieces of state and logic, the Composition API provides a more flexible and maintainable structure.
## Setting Up a Component
A Composition API component uses `
```
## Reactive References vs Reactive Objects
`ref` wraps a single value and requires `.value` access in script but is automatically unwrapped in templates. `reactive` creates a reactive object where properties are directly accessible without `.value`.
```typescript
import { ref, reactive } from 'vue'
// ref — use .value in script
const isLoading = ref(false)
isLoading.value = true
// reactive — direct property access
const formState = reactive({
username: '',
password: '',
errors: []
})
formState.username = 'john_doe'
formState.errors.push('Invalid email')
```
**Rule of thumb**: Use `ref` for primitive values and `reactive` for objects with multiple related properties.
## Watchers and Side Effects
Watchers let you respond to state changes. They are useful for making API calls, logging, or triggering animations when specific values change.
```vue
```
## Composables
Composables are functions that encapsulate reusable stateful logic. They follow a naming convention starting with `use` and return reactive state and methods.
```typescript
// composables/useFetch.ts
import { ref, watchEffect } from 'vue'
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(true)
async function fetchData() {
loading.value = true
error.value = null
try {
const res = await fetch(url.value || url)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
data.value = await res.json()
} catch (err) {
error.value = err.message
} finally {
loading.value = false
}
}
if (typeof url === 'object' && url.value !== undefined) {
watchEffect(fetchData)
} else {
fetchData()
}
return { data, error, loading, refetch: fetchData }
}
```
```vue
```
## Best Practices
- Extract related logic into composables rather than mixing concerns
- Use `ref` for most state; reserve `reactive` for form objects or grouped data
- Always clean up side effects in `onUnmounted`
- Prefer `watchEffect` for automatic dependency tracking over explicit `watch`
- Keep composables pure and testable by avoiding direct DOM access
Count: {{ count }}
Doubled: {{ doubledCount }}
User: {{ user.name }}
Loading...
{{ error }}
- {{ post.title }}
Continue with related content
Suggested next reads and tools from the knowledge graph.