What is keep-alive in Vue: Explanation and Usage
keep-alive in Vue is a built-in component that caches inactive components instead of destroying them, preserving their state and avoiding re-rendering. It helps improve performance and user experience by keeping components alive in memory while switching views.How It Works
Imagine you have a photo album where you flip between pages. Normally, when you close a page, you lose your place and have to start over when you open it again. keep-alive acts like a bookmark that remembers exactly where you left off on each page.
In Vue, when you switch between components, the default behavior is to destroy the old component and create a new one. This means losing any data or scroll position inside it. Wrapping components with keep-alive tells Vue to keep those components in memory, so when you return, they appear instantly with their previous state intact.
This caching happens behind the scenes, so your app feels faster and smoother without extra coding effort.
Example
This example shows two components toggled with keep-alive. The counter value in each component is preserved when switching.
<template>
<div>
<button @click="current = 'A'">Show A</button>
<button @click="current = 'B'">Show B</button>
<keep-alive>
<component :is="current" />
</keep-alive>
</div>
</template>
<script setup>
import { ref } from 'vue'
const current = ref('A')
</script>
<script>
export default {
components: {
A: {
data() {
return { count: 0 }
},
template: `<div>
<p>Component A count: {{ count }}</p>
<button @click="count++">Increment A</button>
</div>`
},
B: {
data() {
return { count: 0 }
},
template: `<div>
<p>Component B count: {{ count }}</p>
<button @click="count++">Increment B</button>
</div>`
}
}
}
</script>When to Use
Use keep-alive when you want to preserve component state between view switches, such as in tabbed interfaces, wizards, or multi-step forms. It avoids reloading data or resetting inputs, making the app feel faster and smoother.
For example, if a user fills part of a form in one tab and switches to another, keep-alive keeps their input intact when they return. It also helps with components that fetch data once and don’t need to reload every time.
Key Points
keep-alivecaches inactive components instead of destroying them.- It preserves component state, data, and DOM.
- Improves performance by avoiding unnecessary re-renders.
- Commonly used in tab views, wizards, and forms.
- Works only with dynamic components or router views.
Key Takeaways
keep-alive caches components to preserve their state and avoid re-creation.keep-alive.