<KeepAlive> component caches component instances when dynamically switching between multiple components, preserving their state and avoiding re-renders.
Basic Usage
<KeepAlive>, component instances are cached instead of being destroyed when they become inactive.
Props
include
- Type:
string | RegExp | Array<string | RegExp>
name option.
exclude
- Type:
string | RegExp | Array<string | RegExp>
max
- Type:
number | string
Lifecycle Hooks
Cached components have access to two special lifecycle hooks:onActivated
Called when a cached component instance is inserted into the DOM.onDeactivated
Called when a cached component instance is removed from the DOM.onActivatedis called on initial mount and every time the component is re-inserted from the cache.onDeactivatedis called when the component is removed from the DOM and also when the entireKeepAlivetree is unmounted.- Both hooks work for the entire component tree, not just the root component wrapped by
<KeepAlive>.
Usage with v-if / v-else
Usage with <Transition>
Caching with Router Views
<KeepAlive> is commonly used with Vue Router to cache route components:
Conditional Caching by Route
You can use route meta fields to selectively cache routes:Component Name Matching
Forinclude and exclude to work properly, components must have a name option:
When using Single-File Components with
<script setup>, the component name is inferred from the filename by default. For explicit control, use defineOptions({ name: 'ComponentName' }).Cache Management
The cache uses an LRU (Least Recently Used) strategy when themax prop is set:
- When a new component is cached and the limit is reached, the least recently accessed cached component is destroyed.
- Each time a cached component is accessed, it’s marked as most recently used.
- Keys are tracked in insertion order, with recently used keys moved to the end.
Implementation Details
- Cache Storage: Uses a
Mapto store cached VNode instances (implementation at/packages/runtime-core/src/components/KeepAlive.ts:111). - Component Detection: Matches against
getComponentName()which checks thenameoption or async component resolution. - State Preservation: Cached components preserve:
- Component instance state
- DOM elements
- Component tree structure
Single Child Requirement
Server-Side Rendering
On the server,<KeepAlive> simply renders its child component without any caching behavior, as caching is only meaningful on the client side.
Source Reference
- Package:
@vue/runtime-core - Implementation:
/packages/runtime-core/src/components/KeepAlive.ts:79-374 - Props Interface:
/packages/runtime-core/src/components/KeepAlive.ts:54-58 - Lifecycle Hooks:
/packages/runtime-core/src/components/KeepAlive.ts:408-420