JAVASCRIPT

Create a Reusable Vue 3 useToggle Composable

Learn to build a simple `useToggle` custom composable in Vue 3 Composition API for managing boolean states efficiently across components.

// 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) => {
    state.value = !!value; // Ensure boolean
  };

  // Optional: Add a computed property to get the current state
  const isEnabled = computed(() => state.value);

  return {
    state,
    toggle,
    set,
    isEnabled
  };
}

// App.vue (Example Usage)
<template>
  <div>
    <button @click="toggle">Toggle State</button>
    <p>Current State: {{ isEnabled ? 'ON' : 'OFF' }}</p>
    <button @click="set(true)">Turn ON</button>
    <button @click="set(false)">Turn OFF</button>
  </div>
</template>

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

const { state, toggle, set, isEnabled } = useToggle(true); // Initial state ON
</script>

<style scoped>
button { margin-right: 10px; }
</style>
How it works: This snippet demonstrates creating a `useToggle` custom composable for managing a boolean state. It leverages Vue 3's `ref` for reactivity and exposes `toggle` and `set` functions to modify the state, along with a `computed` property `isEnabled` for easy access. This pattern promotes reusable logic across components, making it simple to manage ON/OFF states programmatically.

Need help integrating this into your project?

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

Hire DigitalCodeLabs