JAVASCRIPT

Implement a Reusable Toggle Logic with a Vue 3 Composable

Learn how to create a custom Vue 3 Composition API composable (e.g., useToggle) to encapsulate and reuse reactive logic across multiple components, improving code organization and reusability.

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

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

  function toggle() {
    isActive.value = !isActive.value;
  }

  const statusText = computed(() => isActive.value ? 'Active' : 'Inactive');

  return {
    isActive,
    toggle,
    statusText
  };
}

// MyComponent.vue
<template>
  <div>
    <p>Status: {{ statusText }}</p>
    <button @click="toggle">Toggle Status</button>
    <div v-if="isActive">Content is active!</div>
  </div>
</template>

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

const { isActive, toggle, statusText } = useToggle(true);
</script>
How it works: This snippet demonstrates how to create a custom Vue 3 composable, `useToggle`, to encapsulate reusable stateful logic. The composable leverages Vue's `ref` for reactive state and `computed` for derived state, exposing them along with a `toggle` function. Components can then easily import and destructure these properties, promoting modularity and reducing code duplication for common patterns like toggling boolean states.

Need help integrating this into your project?

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

Hire DigitalCodeLabs