JAVASCRIPT

Reusable Logic with Vue 3 Composables

Create a custom composable function in Vue 3's Composition API to encapsulate and reuse reactive stateful logic across multiple components.

// 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 };
}

// AnyComponent.vue
<template>
  <div>
    <p>Mouse Position: {{ x }}, {{ y }}</p>
  </div>
</template>

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

const { x, y } = useMousePosition();
</script>
How it works: This snippet illustrates how to create and use a composable function in Vue 3. A composable, like `useMousePosition`, is a plain JavaScript function that leverages Vue's Composition API to encapsulate reactive state (`ref`) and lifecycle hooks (`onMounted`, `onUnmounted`). It provides a clean way to extract and reuse stateful logic, such as tracking mouse coordinates, across different components without duplication. Components simply import and call the composable, receiving the reactive data it exposes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs