Vue Composables Tips You Need to Know
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:
- Avoid common pitfalls that lead to spaghetti code
- Write composables that are easier to test and maintain
- Create more flexible and reusable shared logic
- Gradually migrate from Options API to Composition API if you need to
The tips you'll learn are:
- Avoid Prop Drilling Through Multiple Components
- Share Data Between Unrelated Components
- Control State Updates with Clear Methods
- Break Up Large Components into Smaller Functions
- Separate Business Logic from Vue Reactivity
- Handle Both Sync and Async Data in One Function
- Make Function Parameters More Descriptive
- Prevent Undefined Options with Default Values
- Return Simple or Complex Values Based on Needs
- Separate Different Logic Paths into Their Own Functions
- Handle Reactive and Raw Values Consistently
- Simplify Ref Unwrapping
- Migrate from Options API to Composition API Gradually
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!
1. Avoid Prop Drilling Through Multiple Components
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) }
2. Share Data Between Unrelated Components
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()
3. Control State Updates with Clear Methods
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) }
4. Break Up Large Components into Smaller Functions
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 })
5. Separate Business Logic from Vue Reactivity
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>
6. Handle Both Sync and Async Data in One Function
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>
7. Make Function Parameters More Descriptive
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 } }
8. Prevent Undefined Options with Default Values
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)
9. Return Simple or Complex Values Based on Needs
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) }
10. Separate Different Logic Paths into Their Own Functions
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 })
11. Handle Reactive and Raw Values Consistently
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>
12. Simplify Ref Unwrapping
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 } }
13. Migrate from Options API to Composition API Gradually
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 }) }
Wrapping it up
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:
- In-depth explanations — when to use it, edge cases, and variations
- Real-world examples — so you can see how to use them beyond these simple examples
- Step-by-step refactoring examples — so you can see how to apply them to your own code
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Data update problems in zustand asynchronous operations. When using the zustand state management library, you often encounter the problem of data updates that cause asynchronous operations to be untimely. �...
