0
0
Vueframework~5 mins

Sharing composables across components in Vue

Choose your learning style9 modes available
Introduction

Sharing composables lets you reuse logic easily in many parts of your app. It keeps your code clean and simple.

You want to use the same reactive data or functions in multiple components.
You need to keep your code DRY (Don't Repeat Yourself) by sharing logic.
You want to separate concerns by moving logic out of components.
You want to test logic separately from UI components.
Syntax
Vue
import { ref } from 'vue';

// useCounter.js
export function useCounter() {
  const count = ref(0);
  function increment() {
    count.value++;
  }
  return { count, increment };
}

// In a component
import { useCounter } from './useCounter';

const { count, increment } = useCounter();

Composable functions start with use by convention.

They return reactive state and functions to use in components.

Examples
A simple toggle composable to share boolean state and toggle function.
Vue
// useToggle.js
import { ref } from 'vue';
export function useToggle(initial = false) {
  const state = ref(initial);
  function toggle() {
    state.value = !state.value;
  }
  return { state, toggle };
}
Using the toggle composable inside a component to get shared logic.
Vue
// In a component
import { useToggle } from './useToggle';

const { state, toggle } = useToggle(true);
Sample Program

This example shows two components using the same composable useCounter. Each has its own count state and increment function. They work independently but share the same logic.

Vue
<script setup>
import { ref } from 'vue';

// useCounter.js
function useCounter() {
  const count = ref(0);
  function increment() {
    count.value++;
  }
  return { count, increment };
}

// Component A
const { count, increment } = useCounter();

// Component B
const { count: countB, increment: incrementB } = useCounter();
</script>

<template>
  <section>
    <h2>Component A</h2>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment A</button>
  </section>
  <section>
    <h2>Component B</h2>
    <p>Count: {{ countB }}</p>
    <button @click="incrementB">Increment B</button>
  </section>
</template>
OutputSuccess
Important Notes

Each call to a composable creates a new independent state.

To share state across components, use a global store or provide/inject.

Summary

Composables let you reuse logic by exporting functions with reactive state.

Import and call composables inside components to get fresh state and methods.

They keep your code clean and easy to maintain.