JAVASCRIPT

Building Reusable Logic with Vue 3 Composables

Learn to create and use Vue 3 Composables to encapsulate and reuse reactive stateful logic across multiple components, improving code organization.

// src/composables/useCounter.js
import { ref, computed } from 'vue';

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

  const increment = () => {
    count.value++;
  };

  const decrement = () => {
    count.value--;
  };

  const isEven = computed(() => count.value % 2 === 0);

  return {
    count,
    increment,
    decrement,
    isEven,
  };
}

// src/components/CounterComponent.vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Is Even: {{ isEven }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
  </div>
</template>

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

const { count, increment, decrement, isEven } = useCounter(10);
</script>
How it works: Composables are functions that leverage Vue's Composition API to encapsulate reusable stateful logic. This `useCounter` composable manages a `count` ref, along with `increment`, `decrement` methods, and an `isEven` computed property. By extracting this logic into a composable, it can be easily imported and reused across any component, promoting code reusability and maintainability without prop drilling or global state.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs