vuejs-composables

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

  • 3 min

In Vue.js, composables are functions that encapsulate reactive logic and can be reused in 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 the 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 that manages 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,
  };
}

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 need to import the function and call it within the setup.

For example, let’s see how to use our composable useCounter 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>

In this example,

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

Practical examples of composables