JAVASCRIPT

Managing Event Listeners with Vue 3 Lifecycle Hooks

Use `onMounted` to add and `onBeforeUnmount` to clean up event listeners in Vue 3 components, preventing memory leaks and ensuring proper resource management.

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const scrollY = ref(0);

function updateScroll() {
  scrollY.value = window.scrollY;
  console.log('Scroll position:', scrollY.value);
}

onMounted(() => {
  // Add event listener when the component is mounted
  window.addEventListener('scroll', updateScroll);
  // Initial call to set the scrollY value
  updateScroll();
});

onBeforeUnmount(() => {
  // Clean up event listener before the component is unmounted
  // This is crucial to prevent memory leaks
  window.removeEventListener('scroll', updateScroll);
  console.log('Scroll listener removed.');
});
</script>

<template>
  <div style="height: 2000px; padding-top: 50px;">
    <h1>Scroll Down to See Updates</h1>
    <p>Current Scroll Position (Y): {{ scrollY }}px</p>
    <p>This component will log scroll position to console.</p>
    <p>Scroll down to see the effect.</p>
    <!-- Dummy content to make the page scrollable -->
    <div v-for="i in 50" :key="i" style="margin-bottom: 20px;">
      Item {{ i }}
    </div>
  </div>
</template>
How it works: This snippet demonstrates the proper way to manage global event listeners using Vue 3's Composition API lifecycle hooks: `onMounted` and `onBeforeUnmount`. When the component is mounted, `onMounted` is used to add a `scroll` event listener to the `window`, updating a reactive `scrollY` ref. Crucially, `onBeforeUnmount` is then used to remove this event listener just before the component is destroyed. This prevents memory leaks and ensures that resources are properly cleaned up, maintaining application performance and stability.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs