JAVASCRIPT
Building a Reusable `useMousePosition` Composable in Vue 3
Learn to encapsulate and reuse reactive logic in Vue 3 with a custom `useMousePosition` composable, providing real-time mouse coordinates to any component.
// 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 using it)
<template>
<div>
<h1>Mouse Position</h1>
<p>X: {{ mouse.x }}</p>
<p>Y: {{ mouse.y }}</p>
<p class="instruction">Move your mouse anywhere on the page!</p>
</div>
</template>
<script setup>
import { useMousePosition } from './composables/useMousePosition';
const mouse = useMousePosition();
</script>
<style scoped>
.instruction {
margin-top: 20px;
font-style: italic;
color: #666;
}
</style>
How it works: This snippet demonstrates creating a reusable Composition API "composable" in Vue 3. The `useMousePosition.js` file exports a function that encapsulates the logic for tracking mouse coordinates. It uses `ref` to create reactive `x` and `y` values and `onMounted`/`onUnmounted` hooks to add and remove a global `mousemove` event listener. Components can then import and call `useMousePosition()` to get reactive access to the mouse coordinates, making the logic highly reusable across the application.