← Back to all snippets
JAVASCRIPT

Vue 3 Composition API: Creating and Using Reusable Composables

Discover how to create and utilize custom composables in Vue 3's Composition API to encapsulate and reuse reactive stateful logic across multiple components efficiently.

// src/composables/useMouseTracker.js
import { ref, onMounted, onUnmounted } from 'vue';

export function useMouseTracker() {
  const x = ref(0);
  const y = ref(0);

  function update(event) {
    x.value = event.pageX;
    y.value = event.pageY;
  }

  onMounted(() => window.addEventListener('mousemove', update));
  onUnmounted(() => window.removeEventListener('mousemove', update));

  return { x, y };
}

// src/components/MouseTrackerDisplay.vue
<template>
  <div>
    Mouse position is at: {{ x }}, {{ y }}
  </div>
</template>

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

const { x, y } = useMouseTracker();
</script>
How it works: This snippet illustrates creating a composable function `useMouseTracker` in Vue 3's Composition API. This composable encapsulates the logic for tracking mouse coordinates and automatically manages event listeners using `onMounted` and `onUnmounted` lifecycle hooks. It then shows how to easily import and use this reusable logic within a component, making the component cleaner and more focused on its specific rendering task.

Need help integrating this into your project?

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

Hire DigitalCodeLabs