Skip to content

Keep Alive

The <keep-alive> component caches inactive components without destroying them, preserving their state.

Use <keep-alive> when you want to maintain the state or avoid re-rendering of dynamic components, such as in tabbed interfaces or route views.

  • Tab navigation where switching tabs should not reset their state.
  • Caching expensive-to-render components.
  • Preserving scroll position or form input.
  • include: Only cache components with matching names.
  • exclude: Do not cache components with matching names.
  • max: Maximum number of component instances to cache.
<keep-alive include="TabA,TabB" max="2">
<component :is="currentTab"></component>
</keep-alive>
<keep-alive>
<component :is="view"></component>
</keep-alive>
  • <keep-alive> only works with dynamic components.
  • Use the activated and deactivated lifecycle hooks to run code when a component is cached or re-activated.
export default {
activated() {
// Called when component is activated by <keep-alive>
},
deactivated() {
// Called when component is deactivated by <keep-alive>
},
};