💻1. What is keep-alive?
Keep-alive is a built-in component of Vue that preserves the state of contained components and prevents them from being re-rendered! Can be understood as body armor 🧥;
For components contained in keep-alive, all views matched by paths are cached.
<keep-alive>
<router-view>
<! All view components that match paths are cached! -->
</router-view>
</keep-alive>
Copy the code
🖱️2. What is the difference between keep-alive and normal components?
Keep-alive is an abstract component that does not render solid nodes. It is rendered by hand with a render function that returns a VNode.
The usual template component is compiled into the render function using Vue for rendering.
🍀3, how to implement the render function in keep-alive?
The created hook function is implemented first, and the render function defines cache and keys to receive caches.
render () {
// Get the default slot, which contains all the contents wrapped by keep-alive
const slot = this.$slots.default
// Get the VNode of the first component node
const vnode: VNode = getFirstComponentChild(slot)
// Get componentOptions for the first component node
constcomponentOptions: ? VNodeComponentOptions = vnode && vnode.componentOption sif (componentOptions) {
// Get the component node name getComponentName
constname: ? string = getComponentName(componentOptions)const { include, exclude } = this
if (
// It does not match included and does not need to be cached(include && (! name || ! matches(include, name))) ||// Component name returned in excluded
(exclude && name && matches(exclude, name))
) {
// If none is present, the current component does not need to be cached and returns VNode directly
return vnode
}
// Get the cache and keys and create a cache for VNode
const { cache, keys } = this
// Define the VNode Key
constkey: ? string = vnode.key ==null
// The same constructor may be registered as different local components
// Select cid from componentOptions; // Select CID from componentOptions
? componentOptions.Ctor.cid + (componentOptions.tag ? ` : :${componentOptions .tag}` : ' ')
: vnode.key // Return the key of the VNode
// If the cache is hit
if (cache[key]) {
// Point VNode's componentInstance to ==> componentInstance
vnode.componentInstance = cache[key].componentInstance
// Remove the old key and push it to the new key
remove(keys, key)
keys.push(key)
} else {
cache[key] = vnode
keys.push(key)
// Clear the cache
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}
vnode.data.keepAlive = true
}
Copy the code
🌵4. Two unique life cycles of Keep-Alive:
The activated and deactivated hook functions are custom hooks for keep-alive components and are not called during rendering.
Activated () : activated when keep-alive is activated.
Deactivated () : called when keep-alive is disabled.