Intermediate LevelVue JS
How do onActivated and onDeactivated lifecycle hooks work with <KeepAlive> components?
❓ Interview Prompt: Explain <KeepAlive> component lifecycles, onActivated() vs onMounted(), and onDeactivated() vs onUnmounted().
When a component is wrapped inside '<KeepAlive>', standard 'onMounted()' and 'onUnmounted()' hooks execute only once during initial creation.
'<KeepAlive>' Lifecycle Hooks:
•
'onActivated()': Fired every time the cached component instance is re-inserted into the DOM (e.g. user switches back to this tab). Use for refreshing live polling data or socket feeds.
•
'onDeactivated()': Fired every time the cached component is removed from the DOM. Use for pausing animations or background audio.
Code Implementation Example
javascript
import { onActivated, onDeactivated } from 'vue';
onActivated(() => {
console.log('Tab became active! Resuming WebSocket data feed.');
});
onDeactivated(() => {
console.log('Tab hidden! Pausing WebSocket data feed.');
});💡Handling tab visibility lifecycle using onActivated and onDeactivated.
🎯 Interview Key Takeaway
Use onActivated and onDeactivated to manage side effects when switching between cached <KeepAlive> components.
#KeepAlive#onActivated#onDeactivated#Intermediate
Back to all Vue JS Questions→