Vue composables are incredibly powerful, but they can quickly become messy and hard to maintain if you're not careful.
That's why I've identified 13 tips that will help you write better, more maintainable composables.
Whether you're building a simple state management solution or complex shared logic, these tips will help you:
The tips you'll learn are:
Let's dive into each pattern and see how they can improve your Vue applications.
And don't forget, comment below with your favourite tip!
The Data Store Pattern can help avoid passing props and events through multiple component layers.
One situation is where you have a parent and child communicating through endless prop drilling and event bubbling:
<!-- Parent.vue --> <template> <!-- But many more layers of components --> <Child :user="user" @change="onUserChange" /> </template> <script setup> const user = ref({ name: 'Alice' }) function onUserChange(updatedUser) { user.value = updatedUser } </script>
This creates a lot of complexity since those props and events have to move back and forth through the component hierarchy.
A more straightforward solution is to create a shared data store that any component can import:
import { reactive, toRefs } from 'vue' const state = reactive({ user: { name: 'Alice' } }) export function useUserStore() { return toRefs(state) }
The Data Store Pattern also helps when sibling or “cousin” components need to share the same data without any direct connection.
Suppose two siblings both require the same user object, but there's no elegant path for props or events.
This often results in awkward data juggling through a parent or duplicated state.
A better approach is to rely on a single composable store that both siblings can consume:
// SiblingA.vue import { useUserStore } from './useUserStore' const { user } = useUserStore() // SiblingB.vue import { useUserStore } from './useUserStore' const { user } = useUserStore()
The Data Store Pattern encourages providing clear methods for updating shared state.
Some developers expose the entire reactive object to the world, like this:
<!-- Parent.vue --> <template> <!-- But many more layers of components --> <Child :user="user" @change="onUserChange" /> </template> <script setup> const user = ref({ name: 'Alice' }) function onUserChange(updatedUser) { user.value = updatedUser } </script>
That lets anybody change the user’s darkMode property directly from any file, which can lead to scattered, uncontrolled mutations.
A better idea is to return the state as read only along with functions that define how updates happen:
import { reactive, toRefs } from 'vue' const state = reactive({ user: { name: 'Alice' } }) export function useUserStore() { return toRefs(state) }
The Inline Composables Pattern helps break up large components by gathering related state and logic into smaller functions.
A giant component might put all its refs and methods in one place:
// SiblingA.vue import { useUserStore } from './useUserStore' const { user } = useUserStore() // SiblingB.vue import { useUserStore } from './useUserStore' const { user } = useUserStore()
That setup quickly becomes unmanageable.
Instead, an inline composable can group logic and provide it locally. We can then extract it into a separate file later on:
export const user = reactive({ darkMode: false })
The Thin Composables Pattern tells us to separate raw business logic from Vue reactivity so tests and maintenance become simpler.
You might embed all logic in the composable:
import { reactive, readonly } from 'vue' const state = reactive({ darkMode: false }) export function toggleDarkMode() { state.darkMode = !state.darkMode } export function useUserStore() { return { darkMode: readonly(state.darkMode), toggleDarkMode } }
That forces you to test logic inside a Vue environment.
Instead, keep the complicated rules in pure functions and let the composable only handle reactive wrappers:
<script setup> const count = ref(0) const user = ref({ name: 'Alice' }) // 500 more lines of intertwined code with watchers, methods, etc. </script>
The Async Sync Composables Pattern merges both synchronous and asynchronous behaviors into one composable instead of creating separate functions.
This is just like how Nuxt's useAsyncData works.
Here we have a single composable that can return a promise while also giving immediate reactive properties for synchronous usage:
<script setup> function useCounter() { const count = ref(0) const increment = () => count.value++ return { count, increment } } const { count, increment } = useCounter() </script>
The Options Object Pattern can clear up long lists of parameters by expecting a single config object.
Calls like this are cumbersome and prone to mistakes, and adding new options requires updating the function signature:
export function useCounter() { const count = ref(0) function increment() { count.value = (count.value * 3) / 2 } return { count, increment } }
It’s not obvious what each argument stands for.
A composable that accepts an options object keeps everything descriptive:
// counterLogic.js export function incrementCount(num) { return (num * 3) / 2 } // useCounter.js import { ref } from 'vue' import { incrementCount } from './counterLogic' export function useCounter() { const count = ref(0) function increment() { count.value = incrementCount(count.value) } return { count, increment } }
The Options Object Pattern also recommends default values for each property.
A function that assumes certain fields exist can be problematic if they aren’t passed:
import { ref } from 'vue' export function useAsyncOrSync() { const data = ref(null) const promise = fetch('/api') .then(res => res.json()) .then(json => { data.value = json return { data } }) return Object.assign(promise, { data }) }
It’s better to destructure options with safe defaults:
useRefHistory(someRef, true, 10, 500, 'click', false)
The Dynamic Return Pattern makes sure a composable can return either a single value for simple use cases or an expanded object with more advanced controls.
Some approaches always return an object with everything:
<!-- Parent.vue --> <template> <!-- But many more layers of components --> <Child :user="user" @change="onUserChange" /> </template> <script setup> const user = ref({ name: 'Alice' }) function onUserChange(updatedUser) { user.value = updatedUser } </script>
Anyone who only needs the main reactive value is forced to deal with extra stuff.
A composable that conditionally returns a single ref or an object solves that:
import { reactive, toRefs } from 'vue' const state = reactive({ user: { name: 'Alice' } }) export function useUserStore() { return toRefs(state) }
The Hidden Composables Pattern helps avoid mixing mutually exclusive logic in the same composable.
Some code lumps together multiple modes or code paths:
// SiblingA.vue import { useUserStore } from './useUserStore' const { user } = useUserStore() // SiblingB.vue import { useUserStore } from './useUserStore' const { user } = useUserStore()
Splitting each path into its own composable is much clearer and doesn't affect functionality:
export const user = reactive({ darkMode: false })
The Flexible Arguments Pattern ensures inputs and outputs in composables are uniformly handled as reactive data or raw values, avoiding confusion.
Some code checks if an input is a ref or not:
import { reactive, readonly } from 'vue' const state = reactive({ darkMode: false }) export function toggleDarkMode() { state.darkMode = !state.darkMode } export function useUserStore() { return { darkMode: readonly(state.darkMode), toggleDarkMode } }
Instead, you can convert right away.
By using ref, if the input is a ref, that ref will be returned. Otherwise, it will be converted to a ref:
<script setup> const count = ref(0) const user = ref({ name: 'Alice' }) // 500 more lines of intertwined code with watchers, methods, etc. </script>
The Flexible Arguments Pattern also uses toValue when unwrapping is needed.
Without it, code might keep doing isRef checks:
<script setup> function useCounter() { const count = ref(0) const increment = () => count.value++ return { count, increment } } const { count, increment } = useCounter() </script>
It’s much simpler to call:
export function useCounter() { const count = ref(0) function increment() { count.value = (count.value * 3) / 2 } return { count, increment } }
The Options to Composition Pattern lets you migrate big Options API components into the Composition API step by step in an incremental way that's easy to follow.
A classic Options component might do this:
// counterLogic.js export function incrementCount(num) { return (num * 3) / 2 } // useCounter.js import { ref } from 'vue' import { incrementCount } from './counterLogic' export function useCounter() { const count = ref(0) function increment() { count.value = incrementCount(count.value) } return { count, increment } }
Data, computed properties, and methods are scattered.
Converting it to script setup pulls them together and makes it easier to follow, and allows you to use these patterns:
import { ref } from 'vue' export function useAsyncOrSync() { const data = ref(null) const promise = fetch('/api') .then(res => res.json()) .then(json => { data.value = json return { data } }) return Object.assign(promise, { data }) }
These 13 tips will help you write better Vue composables that are easier to maintain, test, and reuse across your applications.
But we're just scratching the surface here.
Over the years, I've collected many more patterns and tips, and I've put them all into an in-depth course on composable patterns.
It covers 16 patterns in total, and each pattern has:
Go here to learn more.
Oh, and this course is on sale until January 15th, so you can get it for a great discount right now!
Check out Composable Design Patterns
The above is the detailed content of Vue Composables Tips You Need to Know. For more information, please follow other related articles on the PHP Chinese website!