JAVASCRIPT
Create Reusable Logic with Vue 3 Composition API Composables
Build custom composable functions in Vue 3 to encapsulate and reuse reactive state and logic across multiple components, improving 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 (or any component)
<script setup>
import { useMousePosition } from './composables/useMousePosition';
const { x, y } = useMousePosition();
</script>
<template>
<div>
<h1>Mouse Position</h1>
<p>X: {{ x }}</p>
<p>Y: {{ y }}</p>
</div>
</template>
How it works: Composables are functions that leverage Vue's Composition API to encapsulate stateful logic and make it reusable across components. This example creates a `useMousePosition` composable that tracks the mouse coordinates. It uses `ref` for reactive state, `onMounted` to add an event listener, and `onUnmounted` to clean it up. The component simply imports and calls the composable, destructuring its returned reactive properties.