0
0
Vueframework~5 mins

Composables for reusable logic in Vue

Choose your learning style9 modes available
Introduction

Composables help you share and reuse code easily in Vue. They keep your code clean and organized.

You want to share a piece of logic between multiple components.
You need to keep your component code simple and focused.
You want to separate concerns like fetching data or handling user input.
You want to test logic separately from UI.
You want to avoid repeating the same code in different places.
Syntax
Vue
import { ref } from 'vue';

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

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

  return { state, increment };
}
Composables are regular JavaScript functions that use Vue's reactive features.
They start with 'use' by convention to show they provide reusable logic.
Examples
This composable provides a simple counter with a number and a function to increase it.
Vue
import { ref } from 'vue';

export function useCounter() {
  const count = ref(0);
  function increase() {
    count.value++;
  }
  return { count, increase };
}
This composable tracks the window width and updates reactively when the window resizes.
Vue
import { ref, onMounted, onUnmounted } from 'vue';

export function useWindowWidth() {
  const width = ref(window.innerWidth);

  function updateWidth() {
    width.value = window.innerWidth;
  }

  onMounted(() => {
    window.addEventListener('resize', updateWidth);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', updateWidth);
  });

  return { width };
}
Sample Program

This Vue component uses a composable useToggle to manage a toggle state. The button text changes between ON and OFF when clicked. The aria-pressed attribute improves accessibility by indicating the toggle state to screen readers.

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

function useToggle(initial = false) {
  const isOn = ref(initial);
  function toggle() {
    isOn.value = !isOn.value;
  }
  return { isOn, toggle };
}

const { isOn, toggle } = useToggle();
</script>

<template>
  <button @click="toggle" :aria-pressed="isOn">
    {{ isOn ? 'ON' : 'OFF' }}
  </button>
</template>
OutputSuccess
Important Notes

Always name composables starting with use to keep code clear.

Composables can use Vue's reactive features like ref and reactive.

Use composables to keep components focused on UI, not logic.

Summary

Composables let you reuse logic easily across Vue components.

They are simple functions using Vue's reactive tools.

Use composables to keep your code clean and maintainable.