Keepalive in Vue.js
What is KeepAlive?
<KeepAlive> is a built-in Vue component that caches component instances when they are toggled off, instead of destroying them. This preserves their state and avoids re-mounting.
Without KeepAlive
vue
<template>
<button @click="tab = 'a'">Tab A</button>
<button @click="tab = 'b'">Tab B</button>
<!-- Component is DESTROYED when switching, state is LOST -->
<TabA v-if="tab === 'a'" />
<TabB v-if="tab === 'b'" />
</template>With KeepAlive
vue
<template>
<button @click="tab = 'a'">Tab A</button>
<button @click="tab = 'b'">Tab B</button>
<!-- Component is CACHED when switching, state is PRESERVED -->
<KeepAlive>
<component :is="tab === 'a' ? TabA : TabB" />
</KeepAlive>
</template>Include / Exclude
Control which components are cached:
vue
<!-- Only cache components named TabA and TabB -->
<KeepAlive include="TabA,TabB">
<component :is="currentTab" />
</KeepAlive>
<!-- Cache all except Settings -->
<KeepAlive exclude="Settings">
<component :is="currentTab" />
</KeepAlive>
<!-- Using regex -->
<KeepAlive :include="/^Tab/">
<component :is="currentTab" />
</KeepAlive>Max Cached Instances
vue
<!-- Only keep the 5 most recently used components -->
<KeepAlive :max="5">
<component :is="currentTab" />
</KeepAlive>When the limit is exceeded, the least recently used instance is destroyed.
Lifecycle Hooks
KeepAlive introduces two special lifecycle hooks:
vue
<script setup>
import { onActivated, onDeactivated } from 'vue'
// Called when component is inserted into the DOM from cache
onActivated(() => {
console.log('Component activated — refresh data?')
fetchLatestData()
})
// Called when component is removed from DOM but kept in cache
onDeactivated(() => {
console.log('Component deactivated — pause timers?')
clearInterval(timer)
})
</script>With Vue Router
vue
<!-- App.vue — cache route components -->
<template>
<RouterView v-slot="{ Component }">
<KeepAlive include="Home,Dashboard">
<component :is="Component" />
</KeepAlive>
</RouterView>
</template>Use Cases
| Use Case | Benefit |
|---|---|
| Tab navigation | Preserves form input, scroll position |
| Multi-step forms | User doesn't lose progress |
| List → Detail → Back | List scroll position preserved |
| Dashboard panels | Expensive components stay cached |
Important:
<KeepAlive> caches component instances instead of destroying them, preserving state across toggles. Use include/exclude to control caching, :max to limit memory, and onActivated/onDeactivated hooks for refresh logic. It's essential for tab interfaces and back-navigation UX.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.