JAVASCRIPT
Build Reusable Logic with a Custom Vue 3 Composable
Abstract and reuse reactive logic across multiple Vue 3 components using the Composition API's powerful composables pattern, promoting clean and modular code.
// composables/useToggle.js
import { ref, computed } from 'vue';
export function useToggle(initialValue = false) {
const isActive = ref(initialValue);
const toggle = () => {
isActive.value = !isActive.value;
};
const set = (value) => {
isActive.value = value;
};
// You can also return computed properties or other reactive data
const statusText = computed(() => (isActive.value ? 'Active' : 'Inactive'));
return { isActive, toggle, set, statusText };
}
// MyComponent.vue
<template>
<div>
<p>Status: {{ statusText }} ({{ isActive ? 'ON' : 'OFF' }})</p>
<button @click="toggle">Toggle</button>
<button @click="set(true)">Turn ON</button>
<button @click="set(false)">Turn OFF</button>
<p>Another toggle (independent state):</p>
<p>Status: {{ anotherToggle.statusText }} ({{ anotherToggle.isActive ? 'ON' : 'OFF' }})</p>
<button @click="anotherToggle.toggle">Toggle Another</button>
</div>
</template>
<script setup>
import { useToggle } from './composables/useToggle';
const { isActive, toggle, set, statusText } = useToggle(true);
// Demonstrate independent state for another toggle
const anotherToggle = useToggle();
</script>
How it works: This example showcases a custom Vue 3 composable (`useToggle`) that encapsulates reactive logic for managing a boolean state. Composables are functions that leverage Vue's Composition API to abstract and reuse stateful logic across components. By returning reactive references and functions, `useToggle` allows multiple components to utilize the same toggle functionality with independent states, leading to cleaner, more maintainable, and highly reusable code.