JAVASCRIPT
Creating a Reusable `useToggle` Composable Function
Learn to build a simple yet powerful `useToggle` composable in Vue 3 to manage boolean state, enhancing reusability and keeping components clean.
// composables/useToggle.js
import { ref, computed } from 'vue';
export function useToggle(initialValue = false) {
const state = ref(initialValue);
const toggle = () => {
state.value = !state.value;
};
const set = (value) => {
if (typeof value === 'boolean') {
state.value = value;
} else {
console.warn("useToggle.set expects a boolean value.");
}
};
return {
state: computed(() => state.value), // Return as computed for read-only access in some cases
toggle,
set
};
}
// Component.vue (Example usage)
<template>
<button @click="toggleVisible">{{ isVisible ? 'Hide' : 'Show' }} Content</button>
<p v-if="isVisible">This content is toggled!</p>
<button @click="setVisible(true)">Show Explicitly</button>
<button @click="setVisible(false)">Hide Explicitly</button>
</template>
<script setup>
import { useToggle } from '@/composables/useToggle';
const { state: isVisible, toggle: toggleVisible, set: setVisible } = useToggle(true);
</script>
How it works: This snippet demonstrates how to create a `useToggle` composable, a common pattern in Vue 3 for encapsulating and reusing stateful logic. It provides a reactive `state` (boolean), a `toggle` function to flip the state, and a `set` function to explicitly set it. By abstracting this logic into a composable, you can reuse the boolean toggle functionality across multiple components, making your code cleaner and more maintainable without prop drilling or global state.