JAVASCRIPT
Utilize Lifecycle Hooks in Vue 3's Composition API
Understand how to use `onMounted`, `onUpdated`, `onUnmounted`, and other lifecycle hooks within Vue 3's Composition API `setup` function for robust component control.
<template>
<div>
<h2>Lifecycle Hook Demo</h2>
<p>Message: {{ message }}</p>
<button @click="message = 'Updated Message!'">Update Message</button>
<p v-if="showChild">
<ChildComponent />
</p>
<button @click="showChild = !showChild">Toggle Child Component</button>
</div>
</template>
<script setup>
import { ref, onMounted, onUpdated, onBeforeUnmount, onUnmounted, onRenderTracked, onRenderTriggered } from 'vue';
import ChildComponent from './ChildComponent.vue';
const message = ref('Hello, Vue 3!');
const showChild = ref(true);
onMounted(() => {
console.log('App: Component is mounted (after initial render).');
// Perform DOM manipulations here, or fetch initial data.
});
onUpdated(() => {
console.log('App: Component just updated (DOM has been patched).');
// Called after reactive data changes and DOM updates.
});
onBeforeUnmount(() => {
console.log('App: Component is about to be unmounted.');
// Good for cleanup, e.g., removing event listeners, cancelling timers.
});
onUnmounted(() => {
console.log('App: Component has been unmounted and destroyed.');
// Final cleanup if needed.
});
// Developer-only hooks for debugging reactivity
onRenderTracked((e) => {
console.log('App: Render Tracked:', e);
});
onRenderTriggered((e) => {
console.log('App: Render Triggered:', e);
});
</script>
// ChildComponent.vue
<template>
<div style="border: 1px dashed blue; padding: 10px; margin-top: 10px;">
<h3>I am a Child Component</h3>
<p>Count: {{ count }}</p>
<button @click="count++">Increment Count</button>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const count = ref(0);
let intervalId;
onMounted(() => {
console.log('Child: Component is mounted.');
intervalId = setInterval(() => {
console.log('Child: Interval running...');
}, 2000);
});
onUnmounted(() => {
console.log('Child: Component has been unmounted. Cleaning up interval...');
clearInterval(intervalId);
});
</script>
How it works: Lifecycle hooks allow you to execute code at specific stages of a component's existence, such as when it's mounted to the DOM, updated, or about to be unmounted. In Vue 3's Composition API, these hooks are exposed as functions (e.g., `onMounted`, `onUpdated`, `onUnmounted`) that are imported and called directly within the `setup` function. They provide a powerful way to organize side effects and cleanup logic, ensuring resources are managed correctly throughout the component's lifecycle.