What is keep-alive?
keep-alive is a built-in abstract component of Vue, which is usually used to cache dynamic components or routing components. The component wrapped in keep-alive will not be destroyed during switching, but will be cached. The next time you switch back to this component, the previous instance will be reused and the state will be maintained.
<template> <keep-alive> <component :is="view"></component> </keep-alive> </template> <script> export default { data() { return { view: 'homeComponent' }; } }; </script>
In this example, the homeComponent is not destroyed when switched, but is cached. When displayed again, the status and data remain unchanged.
Keep-alive important configuration options
and exclude: Used to control which components need to be cached, support strings, regular expressions, or arrays.
<keep-alive include="ComponentA, ComponentB" exclude="ComponentC"> <router-view></router-view> </keep-alive>
: Used to specify the number of components cached. When this number exceeds, the longest unused component instance will be destroyed.
<keep-alive :max="6"> <router-view></router-view> </keep-alive>
Life cycle hook
Keep-alive also introduces two new component lifecycle hooks for handling cached components:
- activated: fired when the component is activated (i.e. when recovering from cache)
- deactivated: Triggered when the component is deactivated (i.e. when it is cached)
export default { activated() { ('Component is activated'); }, deactivated() { ('Component is cached'); } };
Applicable scenarios
- Multi-tab switching: In complex forms or multi-step operation scenarios, users frequently switch pages. If you use keep-alive, the switched page can retain the previously entered data or operation status.
- Routing cache: In Vue projects, you often want to keep the component state during routing switching, such as product details pages, search pages, etc.
The core principle of keep-alive
- Cache instance: When the component is loaded for the first time, keep-alive will cache the component's instance.
- Component Reuse: When you switch to a component that has been cached, keep-alive extracts an instance of the component from the cache instead of recreating it.
- Lifecycle Management: To handle component activation and deactivation, keep-alive introduces activated and deactivated hooks, triggered when components enter or leave the cache.
Core principle:
- Cache instance: When the component is loaded for the first time, keep-alive will cache the component's instance.
- Component Reuse: When you switch to a component that has been cached, keep-alive extracts an instance of the component from the cache instead of recreating it.
- Lifecycle Management: To handle component activation and deactivation, keep-alive introduces activated and deactivated hooks, triggered when components enter or leave the cache.
Source code analysis of keep-alive
Some of the principle codes extracted from the following:
export default { name: 'KeepAlive', abstract: true, // This is an abstract component that means it will not be rendered directly to the DOM props: { include: patternTypes, // Components to be cached exclude: patternTypes, // Components that are not cached max: [String, Number] // Maximum cache number }, created () { = (null); // Cache Objects = []; // Used to record the cache order }, destroyed () { for (const key in ) { pruneCacheEntry(, key, ); } }, watch: { include (val) { pruneCache(this, name => matches(val, name)); }, exclude (val) { pruneCache(this, name => !matches(val, name)); } }, render () { const slot = this.$; const vnode = getFirstComponentChild(slot); // Get the first child component if (vnode) { const componentOptions = ; const name = getComponentName(componentOptions); if (name && ( ( && !matches(, name)) || ( && matches(, name)) )) { return vnode; // If the include/exclude does not match, return directly, and do not cache } const key = == null ? + ( ? `::${}` : '') : ; if ([key]) { = [key].componentInstance; // Get the instance from the cache remove(, key); // Remove the old location (key); // Put it back to the end and update the LRU location } else { [key] = vnode; // Cache new instance (key); // If the maximum cache is exceeded, remove the earliest instance if ( && > parseInt()) { pruneCacheEntry(, [0], , this._vnode); } } = true; // Mark the component as keep-alive } return vnode || (slot && slot[0]); // Return to vnode } };
1. Cache mechanism
is an object that stores cached component instances
is an array used to record the order of cache components
2. Cache and activation of components
In the render function, Vue determines whether the current component is within the scope of include and exclude. If the match does not match, no cache will be performed.
Identify the component by key and associate it with the cached instance. If the component is already in the cache, directly remove the cached component instance and reuse it.
Cache Policy
The LRU cache policy maintains an ordered data structure that records the order of use of cache items. When the cache reaches capacity limit, it removes the least recently used items to make room for new data. Common implementations include using a combination of bidirectional linked lists and hash tables to maintain order and fast access to cache items.
When the length exceeds max, delete the earliest cache component (i.e. [0])
4. Life cycle management
activated and deactivated lifecycle hooks are closely related to keep-alive, and they are triggered when components are activated and deactivated from cache. activated and deactivated hooks are used to manage activation and deactivation of components.
This is the end of this article about keep-alive usage guide in vue. For more related vue keep-alive content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!