Vue 3 Composition API Patterns
Learn advanced Vue 3 patterns for building maintainable and scalable applications.
Introduction
The Composition API is a game-changer for Vue.js development. It allows for better logic reuse, type inference, and code organization compared to the Options API.
In this tutorial, we'll explore patterns that go beyond the basics.
Composables: The New Mixins
Composables are functions that encapsulate stateful logic. They are the primary mechanism for code reuse in Vue 3.
Anti-Pattern: Returning a reactive object directly. Pattern: Returning refs.
// useMouse.ts
import { ref, onMounted, onUnmounted } from 'vue'
export function useMouse() {
const x = ref(0)
const y = ref(0)
function update(event) {
x.value = event.pageX
y.value = event.pageY
}
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
return { x, y }
}
Shared State Management
You don't always need Pinia or Vuex. For simple shared state, a composable with state declared outside the function works perfectly.
// store.ts
import { reactive } from 'vue'
const state = reactive({
count: 0
})
export function useStore() {
const increment = () => state.count++
return { state, increment }
}
Async State Pattern
Handling loading, error, and data states for async operations is repetitive. Let's abstract it.
import { ref } from 'vue'
export function useAsync(fn) {
const data = ref(null)
const error = ref(null)
const loading = ref(false)
const execute = async (...args) => {
loading.value = true
error.value = null
try {
data.value = await fn(...args)
} catch (e) {
error.value = e
} finally {
loading.value = false
}
}
return { data, error, loading, execute }
}
Conclusion
The Composition API offers immense flexibility. By following these patterns, you can keep your codebase clean, testable, and scalable.