javascript / intermediate
Snippet
Encapsulating Logic with Composables
Composables allow you to extract stateful logic into reusable functions. By using Vue's lifecycle hooks inside these functions, you can create clean, modular code that is easy to test and share across components.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { onMounted, onUnmounted } from 'vue';export function useMousePosition() {const x = ref(0);const y = ref(0);const update = (e) => {x.value = e.pageX;y.value = e.pageY;};onMounted(() => window.addEventListener('mousemove', update));onUnmounted(() => window.removeEventListener('mousemove', update));return { x, y };}
vue
Breakdown
1
export function useMousePosition()
Naming convention 'use...' identifies this as a Vue Composable.
2
onUnmounted(() => window.removeEventListener(...))
Crucial for preventing memory leaks when the component is destroyed.