← Back to all snippets
JAVASCRIPT

Building Reusable Logic with a Vue 3 Composable

Discover how to create and use Vue 3 Composition API composables to encapsulate and reuse reactive stateful logic across multiple components, enhancing code organization.

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

export function useMousePosition() {
  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 };
}

// App.vue
<template>
  <div>
    <h1>Mouse Position Tracker</h1>
    <p>Mouse X: {{ x }}</p>
    <p>Mouse Y: {{ y }}</p>
  </div>
</template>

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

const { x, y } = useMousePosition();
</script>
How it works: This snippet demonstrates a Vue 3 "composable" - a function that leverages the Composition API to encapsulate stateful logic and make it reusable across components. The `useMousePosition` composable tracks and exposes the current mouse coordinates (`x` and `y`). It uses `onMounted` and `onUnmounted` to manage event listener lifecycle, ensuring clean setup and teardown, making the component using it very clean.

Need help integrating this into your project?

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

Hire DigitalCodeLabs