JAVASCRIPT
Vue 3 Lifecycle Hooks with Composition API
Understand and utilize key Vue 3 lifecycle hooks like `onMounted`, `onUpdated`, and `onUnmounted` within the Composition API for component management.
<template>
<div class="lifecycle-demo">
<h2>Lifecycle Hook Demo</h2>
<p>Count: {{ count }}</p>
<button @click="count++">Increment Count</button>
</div>
</template>
<script setup>
import { ref, onMounted, onUpdated, onUnmounted } from 'vue';
const count = ref(0);
// Executed once after the component is mounted to the DOM.
onMounted(() => {
console.log('Component mounted!');
});
// Executed after the component has updated its DOM tree.
onUpdated(() => {
console.log('Component updated! Count is now: ' + count.value);
});
// Executed just before the component is unmounted from the DOM.
onUnmounted(() => {
console.log('Component unmounted!');
// Clean up any timers, event listeners, etc. here
});
</script>
<style scoped>
.lifecycle-demo {
border: 1px solid purple;
padding: 15px;
margin-top: 15px;
}
</style>
How it works: This snippet demonstrates essential Vue 3 lifecycle hooks using the Composition API. `onMounted` runs once the component has been added to the DOM, often used for initial data fetching or DOM manipulations. `onUpdated` triggers after the component's DOM has been updated in response to reactive state changes. `onUnmounted` executes just before the component is removed from the DOM, making it ideal for cleaning up resources like timers or event listeners to prevent memory leaks. Interacting with the counter will show `onUpdated` in action.