JAVASCRIPT
Creating Reusable Composables for Reactive Logic in Vue 3
Learn to build custom composables (Vue 3 hooks) to encapsulate and reuse reactive stateful 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 };
}
// MyComponent.vue
<template>
<div>Mouse position is at: {{ x }}, {{ y }}</div>
</template>
<script setup>
import { useMousePosition } from './composables/useMousePosition';
const { x, y } = useMousePosition();
</script>
How it works: This snippet shows how to create a reusable composable function in Vue 3's Composition API. The `useMousePosition` composable encapsulates logic for tracking mouse coordinates, including setting up and tearing down event listeners. Components can then easily consume this reactive logic by calling the composable, leading to cleaner and more maintainable code through shared functionality.