Vue 3 Composition API - A Deep Dive
Explore the Vue 3 Composition API and learn how to write more organized, reusable, and maintainable Vue components.
Vue 3 Composition API - A Deep Dive
The Composition API is one of the most exciting features in Vue 3. It provides a new way to organize component logic that's more flexible and reusable than the Options API.
Why Composition API?
The Composition API solves several problems:
- Better code organization - Group related logic together
- Improved reusability - Extract and share logic easily
- Better TypeScript support - Type inference just works
- No
thisconfusion - Everything is explicit
Basic Setup
Here's a simple component using the Composition API:
<script setup>
import { ref, computed } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
function increment() {
count.value++
}
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<p>Doubled: {{ doubled }}</p>
<button @click="increment">Increment</button>
</div>
</template>
Reactive State
Vue 3 provides two ways to create reactive state:
ref()
Use ref() for primitive values:
import { ref } from 'vue'
const count = ref(0)
const message = ref('Hello')
// Access value with .value
console.log(count.value) // 0
count.value++
reactive()
Use reactive() for objects:
import { reactive } from 'vue'
const state = reactive({
count: 0,
user: {
name: 'John',
email: 'john@example.com'
}
})
// No .value needed
console.log(state.count) // 0
state.count++
Composables
Extract reusable logic into composables:
// composables/useCounter.js
import { ref } from 'vue'
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
function increment() {
count.value++
}
function decrement() {
count.value--
}
function reset() {
count.value = initialValue
}
return {
count,
increment,
decrement,
reset
}
}
Use it in any component:
<script setup>
import { useCounter } from '@/composables/useCounter'
const { count, increment, decrement, reset } = useCounter(10)
</script>
Lifecycle Hooks
All lifecycle hooks are available:
import { onMounted, onUnmounted } from 'vue'
onMounted(() => {
console.log('Component mounted')
})
onUnmounted(() => {
console.log('Component unmounted')
})
Watch and WatchEffect
Monitor reactive state changes:
import { ref, watch, watchEffect } from 'vue'
const count = ref(0)
// Watch specific source
watch(count, (newValue, oldValue) => {
console.log(`Count changed from ${oldValue} to ${newValue}`)
})
// Watch multiple sources
watch([count, message], ([newCount, newMessage]) => {
console.log('Something changed')
})
// Auto-track dependencies
watchEffect(() => {
console.log(`Count is ${count.value}`)
})
Computed Properties
Create derived state:
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed(() => {
return `${firstName.value} ${lastName.value}`
})
// Writable computed
const fullNameWritable = computed({
get() {
return `${firstName.value} ${lastName.value}`
},
set(value) {
[firstName.value, lastName.value] = value.split(' ')
}
})
Best Practices
- Use
<script setup>- It's more concise and performant - Extract reusable logic - Create composables for shared functionality
- Keep composables focused - Each composable should do one thing well
- Use TypeScript - Get better type inference and autocomplete
Conclusion
The Composition API is a game-changer for Vue development. It makes your code more organized, reusable, and maintainable. Start using it in your next project!
