What is onActivated and onDeactivated in Vue: Simple Explanation
onActivated and onDeactivated are Vue lifecycle hooks used with <keep-alive> components to run code when a component is activated or deactivated without being destroyed. onActivated runs when the component becomes active, and onDeactivated runs when it becomes inactive but stays in memory.How It Works
Imagine you have a favorite book that you sometimes put away on a shelf but want to keep it open to the same page when you come back. In Vue, <keep-alive> works like that shelf, keeping components alive in memory even when they are not visible.
The onActivated hook runs when you take the book off the shelf and start reading again, letting you refresh or resume things. The onDeactivated hook runs when you put the book back on the shelf, allowing you to pause or save state without fully closing the book (destroying the component).
This helps Vue apps keep components ready and fast without losing their state, unlike normal mounting and unmounting which fully resets components.
Example
This example shows a component that logs messages when it is activated or deactivated inside a <keep-alive> wrapper.
<template>
<div>
<button @click="show = !show">Toggle Component</button>
<keep-alive>
<MyComponent v-if="show" />
</keep-alive>
</div>
</template>
<script setup>
import { ref } from 'vue'
const show = ref(true)
const MyComponent = {
template: `<div>Component is active</div>`,
setup() {
onActivated(() => {
console.log('Component activated')
})
onDeactivated(() => {
console.log('Component deactivated')
})
}
}
</script>When to Use
Use onActivated and onDeactivated when you want to keep a component alive but react to it being shown or hidden. This is common in tabbed interfaces or pages cached with <keep-alive>.
For example, you might refresh data when a tab becomes active or pause a video when the tab is hidden without destroying the component. This improves performance and user experience by avoiding full reloads.
Key Points
onActivatedruns when a kept-alive component becomes visible.onDeactivatedruns when it becomes hidden but stays in memory.- They only work inside
<keep-alive>wrappers. - Useful for caching state and controlling behavior without full remount.
- Helps improve app speed and smoothness in tab or view switching.