Vue.jsApril 8, 2026
Vue Composables: Patterns and Best Practices
Learn how to create and use composables effectively in your Vue applications.
Composables are functions that leverage Vue’s Composition API to encapsulate and reuse stateful logic.
Creating a Composable
js
// composables/useMouse.js
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 }
}
Using Composables
vue
<script setup>
import { useMouse } from '@/composables/useMouse'
const { x, y } = useMouse()
</script>
<template>
<p>Mouse position: {{ x }}, {{ y }}</p>
</template>
Async Composable Pattern
js
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(true)
fetch(url)
.then(res => res.json())
.then(json => {
data.value = json
})
.catch(err => {
error.value = err
})
.finally(() => {
loading.value = false
})
return { data, error, loading }
}
Best Practices
- Start with
useprefix - Return refs, not raw values
- Handle cleanup in
onUnmounted - Keep composables focused and small