vuejs-composables

What are Composables and how to use them in Vue.js

  • 4 min

In Vue.js, composables are functions that encapsulate reactive logic and can be reused across multiple components.

Composables allow us to organize and reuse logic in a modular way, which is especially useful in complex applications.

They are an evolution of the mixins that existed in Vue.js 2, but more flexible and easier to maintain. If you see mixins, it’s an obsolete syntax.

Basic Syntax of a Composable

A composable is simply a function that uses Composition API functions, (like ref, reactive, computed, and watch).

By convention, composables are named starting with ‘use’. But it’s just a convention.

Otherwise, they are “normal” functions. They can return reactive values, methods, or any other logic we need.

Let’s see an example by creating a composable to manage the state of a counter. For this, we create the file useCounter.js, with this content.

import { ref } from 'vue';

export function useCounter() {
  const count = ref(0);

  function increment() {
    count.value++;
  }

  function decrement() {
    count.value--;
  }

  return {
    count,
    increment,
    decrement,
  };
}
Copied!

In this example,

  • useCounter is a composable that encapsulates the logic of a counter.
  • It returns a reactive value (count) and two methods (increment and decrement).

Using a Composable in a Component

Now we can use our composable in our component. To do this, we simply have to import the function and call it inside setup.

For example, let’s see how to use our useCounter composable in a component.

<script setup>
import { useCounter } from './useCounter';

const { count, increment, decrement } = useCounter();
</script>

<template>
  <div>
    <p>Counter: {{ count }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
  </div>
</template>
Copied!

In this example,

  • The component uses the useCounter composable to manage the counter state.
  • The counter logic is encapsulated in the composable, making the component cleaner and easier to maintain.

Practical Examples of Composables