JAVASCRIPT
Implement Reusable Logic with Vue 3 Composables
Learn how to create and use Vue 3 composable functions to encapsulate and reuse reactive stateful logic across multiple components, improving code organization and maintainability.
// 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
};
}
// App.vue (example usage)
<template>
<div>
<h1>Counter 1: {{ count }} (Double: {{ doubleCount }})</h1>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
<div>
<h1>Counter 2: {{ count2 }}</h1>
<button @click="increment2">Increment</button>
</div>
</template>
<script setup>
import { useCounter } from './useCounter.js';
const { count, increment, decrement, doubleCount } = useCounter(10); // Counter 1
const { count: count2, increment: increment2 } = useCounter(5); // Counter 2, independent state
</script>
How it works: This snippet demonstrates creating a `useCounter` composable function. It encapsulates `count` (a reactive ref), `increment`, `decrement` methods, and a `doubleCount` computed property. By importing and using `useCounter` in `App.vue`, the same logic can be reused in multiple places with independent state, promoting clean, modular, and reusable code, a core principle of the Vue 3 Composition API.