JAVASCRIPT
Utilizing Lifecycle Hooks with Vue 3 Composition API
Understand and implement essential Vue 3 lifecycle hooks like `onMounted` and `onUnmounted` using the Composition API for setup and cleanup logic.
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
const message = ref('Hello, Vue 3!');
let intervalId = null;
onMounted(() => {
// This code runs after the component has been mounted to the DOM.
console.log('Component is mounted! Message:', message.value);
// Example: Start an interval that updates the message every 2 seconds
intervalId = setInterval(() => {
message.value = `Updated at: ${new Date().toLocaleTimeString()}`;
console.log('Message updated by interval.');
}, 2000);
});
onBeforeUnmount(() => {
// This code runs before the component is unmounted from the DOM.
// Ideal for cleaning up side effects like timers, event listeners, etc.
if (intervalId) {
clearInterval(intervalId);
console.log('Interval cleared before component unmount.');
}
console.log('Component is about to be unmounted.');
});
</script>
<template>
<div>
<h1>Lifecycle Hook Demo</h1>
<p>{{ message }}</p>
<p>(Check console for lifecycle logs)</p>
</div>
</template>
How it works: This snippet illustrates the use of key lifecycle hooks in Vue 3's Composition API: `onMounted` and `onBeforeUnmount`. `onMounted` is called once after the component has been inserted into the DOM, making it an ideal place to perform initial data fetching, DOM manipulation, or set up global event listeners. `onBeforeUnmount` is called right before a component instance is unmounted. It's crucial for cleaning up any side effects initiated during the component's lifetime, such as clearing timers (`setInterval`, `setTimeout`), removing event listeners, or canceling network requests, to prevent memory leaks and unexpected behavior.