0
0
Vueframework~5 mins

Creating a custom composable in Vue

Choose your learning style9 modes available
Introduction

A custom composable lets you reuse logic easily in Vue components. It keeps your code clean and organized.

You want to share reactive state or functions between multiple components.
You need to separate complex logic from the template for clarity.
You want to keep your components small and focused.
You want to reuse code like fetching data or handling user input.
You want to test logic separately from UI.
Syntax
Vue
import { ref, computed } from 'vue';

export function useCustomLogic() {
  const state = ref(0);

  function updateState(newValue) {
    state.value = newValue;
  }

  const derivedValue = computed(() => state.value * 2);

  return { state, updateState, derivedValue };
}
A composable is a regular function that uses Vue's reactive APIs like ref or computed.
It returns reactive data and functions to be used in components.
Examples
A simple counter composable that tracks a number and increases it.
Vue
import { ref } from 'vue';

export function useCounter() {
  const count = ref(0);
  function increment() {
    count.value++;
  }
  return { count, increment };
}
This composable logs input changes to the console.
Vue
import { ref, watch } from 'vue';

export function useInputLogger() {
  const input = ref('');
  watch(input, (newVal) => {
    console.log('Input changed to:', newVal);
  });
  return { input };
}
Sample Program

This Vue component uses the useCounter composable to show a button. Clicking it increases the count shown.

It uses semantic HTML and an ARIA label for accessibility.

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

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

<template>
  <button @click="increment" aria-label="Increase count">Count is: {{ count }}</button>
</template>
OutputSuccess
Important Notes

Always prefix composable functions with use to follow Vue community conventions.

Keep composables focused on one task for easier reuse and testing.

Use ref for reactive variables and computed for derived values inside composables.

Summary

Custom composables help reuse reactive logic across Vue components.

They are simple functions using Vue's reactive APIs and return reactive data and methods.

Use composables to keep components clean, testable, and organized.