← Back to all snippets
JAVASCRIPT

Creating Reusable Logic with Vue 3 Composables

Discover how to build and integrate composables in Vue 3's Composition API to encapsulate and reuse reactive stateful logic across multiple components.

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

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

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

  // Optional: side effect based on isActive
  watchEffect(() => {
    // console.log(`Toggle state is now: ${isActive.value}`);
  });

  return { isActive, toggle };
}

// App.vue (example usage)
<template>
  <div>
    <p>Toggle State: {{ isActive ? 'ON' : 'OFF' }}</p>
    <button @click="toggle">Toggle</button>

    <p>Another Toggle State: {{ otherToggle.isActive ? 'Active' : 'Inactive' }}</p>
    <button @click="otherToggle.toggle">Toggle Other</button>
  </div>
</template>

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

const { isActive, toggle } = useToggle(true); // Initial state true
const otherToggle = useToggle(); // Initial state false by default
</script>
How it works: Composables in Vue 3's Composition API are functions that encapsulate reusable stateful logic. This `useToggle` composable demonstrates how to create a reactive `isActive` state and a `toggle` function. Components can then import and use this composable, allowing shared logic to be reused across different parts of the application without prop drilling or global state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs