JAVASCRIPT
Manage Global Event Listeners with Vue 3 Lifecycle Hooks
Learn to effectively add and remove global event listeners in Vue 3 using `onMounted` and `onUnmounted` hooks, ensuring proper resource management and preventing memory leaks.
// components/MouseTracker.vue
<template>
<div>
<h2>Mouse Position Tracker</h2>
<p>X: {{ x }}</p>
<p>Y: {{ y }}</p>
<p>(Move your mouse anywhere on the page)</p>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const x = ref(0);
const y = ref(0);
const updateMousePosition = (event) => {
x.value = event.pageX;
y.value = event.pageY;
};
onMounted(() => {
window.addEventListener('mousemove', updateMousePosition);
console.log('mousemove listener added!');
});
onUnmounted(() => {
window.removeEventListener('mousemove', updateMousePosition);
console.log('mousemove listener removed!');
});
</script>
How it works: This snippet demonstrates the crucial role of `onMounted` and `onUnmounted` lifecycle hooks in Vue 3's Composition API. `onMounted` is used to add a global `mousemove` event listener to the `window` object when the component is first mounted to the DOM. Crucially, `onUnmounted` is used to remove this same listener when the component is unmounted, preventing memory leaks and ensuring proper resource cleanup, which is vital for application performance and stability.