JAVASCRIPT

Creating a Reusable Toggle State with a Vue 3 Composable

Learn to build a custom Vue 3 composable (`useToggle`) for managing boolean states, enhancing code 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) => {
    state.value = value;
  };

  return {
    state: computed(() => state.value), // Return computed to make it read-only outside
    toggle,
    set,
  };
}

// App.vue (example usage)
<template>
  <div>
    <p>Current state: {{ isActive }}</p>
    <button @click="toggleActive">Toggle</button>
    <button @click="setActive(true)">Set Active</button>
    <button @click="setActive(false)">Set Inactive</button>
  </div>
</template>

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

const { state: isActive, toggle: toggleActive, set: setActive } = useToggle(false);
</script>
How it works: This snippet demonstrates creating a `useToggle` composable, a powerful pattern for encapsulating reusable logic in Vue 3. It uses `ref` to manage a boolean state and exposes methods (`toggle`, `set`) to modify it, along with a `computed` property for the state. This keeps component scripts clean and promotes consistent state management across your application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs