search
HomeWeb Front-endJS TutorialVue Composables Tips You Need to Know

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:

  1. Avoid Prop Drilling Through Multiple Components
  2. Share Data Between Unrelated Components
  3. Control State Updates with Clear Methods
  4. Break Up Large Components into Smaller Functions
  5. Separate Business Logic from Vue Reactivity
  6. Handle Both Sync and Async Data in One Function
  7. Make Function Parameters More Descriptive
  8. Prevent Undefined Options with Default Values
  9. Return Simple or Complex Values Based on Needs
  10. Separate Different Logic Paths into Their Own Functions
  11. Handle Reactive and Raw Values Consistently
  12. Simplify Ref Unwrapping
  13. 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"></child>
</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"></child>
</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"></child>
</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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment