Welcome to The Coding College! In this tutorial, we’ll delve into the deactivated
lifecycle hook in Vue.js. This hook complements the activated
hook and is a crucial feature when working with cached components inside <KeepAlive>
.
What is the deactivated
Lifecycle Hook?
The deactivated
hook in Vue.js is triggered when a component wrapped inside a <KeepAlive>
becomes inactive (hidden). This hook enables developers to handle cleanup, pause operations, or release resources for cached components without destroying their state.
When Does deactivated
Trigger?
The deactivated
hook fires when:
- A component inside a
<KeepAlive>
is swapped out or hidden. - The component is not destroyed but is removed from the active view.
It pairs with the activated
hook, which runs when the same component becomes active again.
Syntax
Using the Options API
<script>
export default {
deactivated() {
console.log('Component deactivated');
},
activated() {
console.log('Component activated');
}
};
</script>
Using the Composition API
import { onDeactivated, onActivated } from 'vue';
export default {
setup() {
onDeactivated(() => {
console.log('Component deactivated');
});
onActivated(() => {
console.log('Component activated');
});
}
};
Example: Managing Cached Components
Code Example
<template>
<div>
<button @click="currentView = 'ComponentA'">Show Component A</button>
<button @click="currentView = 'ComponentB'">Show Component B</button>
<KeepAlive>
<component :is="currentView" />
</KeepAlive>
</div>
</template>
<script>
export default {
data() {
return {
currentView: 'ComponentA'
};
},
components: {
ComponentA: {
template: `<p>Component A</p>`,
activated() {
console.log('Component A activated');
},
deactivated() {
console.log('Component A deactivated');
}
},
ComponentB: {
template: `<p>Component B</p>`,
activated() {
console.log('Component B activated');
},
deactivated() {
console.log('Component B deactivated');
}
}
}
};
</script>
Example Output
When switching between the components:
- Viewing Component A:
Component A activated
- Switching to Component B:
Component A deactivated
Component B activated
Use Cases for deactivated
1. Pausing Timers or Animations
Pause ongoing animations, timers, or intervals when the component becomes inactive.
deactivated() {
clearInterval(this.timer);
console.log('Timer paused');
}
2. Releasing Resources
Free up memory or stop resource-intensive operations when the component is hidden.
deactivated() {
this.cleanupNetworkRequests();
console.log('Network requests cleaned up');
}
3. Managing State
Save the component’s current state or data for reuse when it becomes active again.
data() {
return { formState: {} };
},
deactivated() {
console.log('Saving form state:', this.formState);
}
Advanced Example
Pausing a Timer on Deactivation
<template>
<KeepAlive>
<TimerComponent />
</KeepAlive>
</template>
<script>
export default {
components: {
TimerComponent: {
data() {
return {
seconds: 0,
timer: null
};
},
template: `<p>{{ seconds }} seconds passed</p>`,
methods: {
startTimer() {
this.timer = setInterval(() => {
this.seconds++;
}, 1000);
},
stopTimer() {
clearInterval(this.timer);
}
},
activated() {
this.startTimer();
console.log('Timer resumed');
},
deactivated() {
this.stopTimer();
console.log('Timer paused');
}
}
}
};
</script>
Output
- When the timer component becomes active:
Timer resumed
- When the timer component is hidden:
Timer paused
Best Practices for Using deactivated
- Optimize Resource Management
Usedeactivated
to pause operations like network requests, intervals, or event listeners to avoid performance bottlenecks. - Combine with
activated
Use theactivated
anddeactivated
hooks together for a seamless experience in cached components. - Avoid State Loss
Ensure critical state information is preserved when a component is deactivated, so it can be reused when activated. - Test Cached Behaviors
Always test how cached components behave to avoid unexpected issues, especially with reactive dependencies.
Limitations
- Only for
<KeepAlive>
: Thedeactivated
hook is exclusive to cached components within<KeepAlive>
. - Not for Destroyed Components: Components that are destroyed don’t trigger
deactivated
. UsebeforeUnmount
for cleanup in those cases.
Conclusion
The deactivated
lifecycle hook is a powerful tool for managing the lifecycle of cached components in Vue. It allows developers to optimize performance, manage resources, and ensure smooth transitions between active and inactive states.
Key Takeaways:
- Use
deactivated
to handle cleanup or pause operations for inactive components. - Pair it with
activated
for complete control over cached component states. - Essential for applications that use dynamic components with
<KeepAlive>
.
For more insights and advanced Vue.js tutorials, visit The Coding College!