JAVASCRIPT
Building Reusable Logic with Vue 3 Composables (Custom Hooks)
Master creating powerful, shareable logic for your Vue 3 components using the Composition API's composables, improving code organization and reusability.
// 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
};
}
// MyComponent.vue
<template>
<div>
<h2>Counter Component</h2>
<p>Count: {{ count }}</p>
<p>Double Count: {{ doubleCount }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
<script setup>
import { useCounter } from '../composables/useCounter';
// Use the composable with an initial value
const { count, increment, decrement, doubleCount } = useCounter(10);
</script>
<style scoped>
button {
margin-right: 10px;
padding: 8px 15px;
border: 1px solid #ccc;
border-radius: 4px;
cursor: pointer;
}
</style>
How it works: This snippet illustrates how to create and use a Vue 3 composable (a custom hook) to encapsulate reusable reactive logic. The `useCounter.js` file defines a `useCounter` function that manages a `count` ref, provides methods to increment and decrement it, and a `doubleCount` computed property. This logic is then consumed in `MyComponent.vue` using `script setup`, where the returned reactive properties and methods from `useCounter` can be directly destructured and used in the template, promoting clean and modular code.