JAVASCRIPT
Creating a Reusable Mouse Tracking Composable in Vue 3
Build a custom Vue 3 composable to encapsulate and reuse mouse position tracking logic across multiple components, enhancing modularity and code reuse.
// composables/useMousePosition.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useMousePosition() {
const x = ref(0);
const y = ref(0);
function update(e) {
x.value = e.pageX;
y.value = e.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.js';
const { x, y } = useMousePosition();
</script>
<template>
<div>
<h1>Mouse Position Tracker</h1>
<p>X: {{ x }}</p>
<p>Y: {{ y }}</p>
</div>
</template>
How it works: This snippet demonstrates creating a custom Vue 3 composable named `useMousePosition`. Composables are functions that encapsulate stateful logic and can be reused across different components. This specific composable tracks the mouse coordinates (`x` and `y`) by adding and removing a `mousemove` event listener during the component's mounted and unmounted lifecycle phases, respectively. By extracting this logic into a composable, you can easily add mouse tracking functionality to any component with a single line of code, promoting code organization and reusability.