javascript / intermediate
Snippet
Reusable Logic with Composables
Composables are functions that leverage Vue's Composition API to encapsulate and reuse stateful logic across components. They replace older patterns like Mixins by providing better type safety and preventing namespace collisions.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { ref, onMounted, onUnmounted } from 'vue';export function useMouse() {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 };}
vue
Breakdown
1
const x = ref(0);
Initialize a reactive reference for the horizontal coordinate.
2
onMounted(() => ...)
Register the event listener only after the component is added to the DOM.
3
onUnmounted(() => ...)
Clean up the listener to prevent memory leaks when the component is destroyed.