JAVASCRIPT
Create Reusable Logic with Vue 3 Composables
Discover how to build and use custom composables in Vue 3's Composition API to encapsulate and reuse reactive stateful logic across multiple components efficiently.
// 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 doubleCount = computed(() => count.value * 2);
return {
count,
increment,
decrement,
doubleCount,
};
}
// src/components/MyComponent.vue
<template>
<div>
<p>Counter: {{ count }}</p>
<p>Double Counter: {{ doubleCount }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
<script setup>
import { useCounter } from '../composables/useCounter';
const { count, increment, decrement, doubleCount } = useCounter(10);
</script>
How it works: This snippet illustrates the power of Vue 3 Composables. The `useCounter.js` file defines a composable function that encapsulates reusable counting logic, including reactive state (`count`) and methods (`increment`, `decrement`, `doubleCount`). `MyComponent.vue` then imports and uses this composable, making the logic easily shareable and testable across multiple components without prop drilling or complex inheritance.