JAVASCRIPT
Using Lifecycle Hooks with Composition API in Vue 3
Master Vue 3 component lifecycle with `onMounted`, `onUpdated`, `onBeforeUnmount`, and `onErrorCaptured` in Composition API `script setup` for robust components.
<script setup>
import { ref, onMounted, onUpdated, onBeforeUnmount, onErrorCaptured } from 'vue';
const count = ref(0);
const timer = ref(null);
onMounted(() => {
console.log('Component mounted: DOM is ready and accessible.');
// Simulate an interval that updates the count
timer.value = setInterval(() => {
count.value++;
}, 1000);
});
onUpdated(() => {
console.log('Component updated: DOM has been re-rendered.');
// This will log every second due to count.value++
});
onBeforeUnmount(() => {
console.log('Component about to be unmounted: Clean up side effects.');
// Clear the interval to prevent memory leaks
if (timer.value) {
clearInterval(timer.value);
timer.value = null;
}
});
// Simulate an error for onErrorCaptured
const triggerError = () => {
throw new Error('An intentional error occurred!');
};
onErrorCaptured((err, instance, info) => {
console.error('Caught an error in a child component or within this component:', err.message);
console.log('Error instance:', instance);
console.log('Error info:', info);
// Return false to prevent the error from propagating further up the component tree
return false;
});
</script>
<template>
<div>
<h2>Lifecycle Hooks Example</h2>
<p>Count: {{ count }}</p>
<p>Check the console for lifecycle hook logs.</p>
<button @click="triggerError">Trigger Error</button>
<p>Unmount this component to see onBeforeUnmount in action.</p>
</div>
</template>
How it works: This snippet demonstrates common lifecycle hooks in Vue 3's Composition API using `script setup`. `onMounted` runs after the component is first rendered, ideal for initial data fetching or DOM manipulation. `onUpdated` triggers after the component's reactivity changes and the DOM is re-rendered. `onBeforeUnmount` is crucial for cleanup tasks like clearing timers or event listeners before the component is removed. `onErrorCaptured` provides a way to gracefully handle errors propagated from child components or within the component itself.