JAVASCRIPT

Create a Reusable useToggle Composable for Vue 3

Implement a `useToggle` composable in Vue 3's Composition API to easily manage boolean state, enhancing code reusability and simplifying component logic.

// composables/useToggle.js
import { ref, computed } from 'vue';

export function useToggle(initialValue = false) {
  const state = ref(initialValue);

  const toggle = () => {
    state.value = !state.value;
  };

  const setTrue = () => {
    state.value = true;
  };

  const setFalse = () => {
    state.value = false;
  };

  return {
    state: computed(() => state.value), // Expose as computed to prevent direct mutation outside the composable
    toggle,
    setTrue,
    setFalse
  };
}

// App.vue (or any component)
<template>
  <div>
    <p>Current state: {{ isOn }}</p>
    <button @click="toggle()">Toggle</button>
    <button @click="setTrue()">Set True</button>
    <button @click="setFalse()">Set False</button>

    <p>Another state: {{ isVisible }}</p>
    <button @click="toggleVisibility()">Toggle Visibility</button>
  </div>
</template>

<script setup>
import { useToggle } from './composables/useToggle';

const { state: isOn, toggle, setTrue, setFalse } = useToggle(true);
const { state: isVisible, toggle: toggleVisibility } = useToggle(); // defaults to false
</script>
How it works: This snippet demonstrates creating a custom Vue 3 composable, `useToggle`, which encapsulates logic for managing a boolean state. It uses `ref` for reactivity and exposes methods (`toggle`, `setTrue`, `setFalse`) to manipulate the state, along with the `state` itself as a computed property. This pattern promotes code reusability across multiple components, keeping component logic clean and focused.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs