keep-alive
props:
include - 字符串或正则表达式。只有名称匹配的组件会被缓存。
exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。
max - 数字。最多可以缓存多少组件实例。
用法:
包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和transition 相似, keep-alive是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在父组件链中。
当组件在 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。
主要用于保留组件状态或避免重新渲染。
源码解析
/* @flow */
/**
* 引用工具函数:
* isRegExp : 判断是否是正则表达式
* remove: 从数组中删除某一项
* getFirstComponentChild:
*/
import { isRegExp, remove } from 'shared/util'
import { getFirstComponentChild } from 'core/vdom/helpers/index'
/**
*第一个行有个注释 @flow,基于FLOW去做的类型检查
* 表示引用一个复杂类型,[]表示可以通过key进行索引,?表示值的类型是可选的
**/
type VNodeCache = { [key: string]: ?VNode };
/**
* 获取组件名称:
* 如果option中有定义name属性则直接返回
* 否则返回tag
*/
function getComponentName (opts: ?VNodeComponentOptions): ?string {
return opts && (opts.Ctor.options.name || opts.tag)
}
/**
* 匹配规则
*/
function matches (pattern: string | RegExp | Array<string>, name: string): boolean {
if (Array.isArray(pattern)) {
return pattern.indexOf(name) > -1
} else if (typeof pattern === 'string') {
return pattern.split(',').indexOf(name) > -1
} else if (isRegExp(pattern)) {
return pattern.test(name)
}
/* istanbul ignore next */
return false
}
/**
* 修剪缓存
*/
function pruneCache (keepAliveInstance: any, filter: Function) {
const { cache, keys, _vnode } = keepAliveInstance
for (const key in cache) {
const cachedNode: ?VNode = cache[key]
if (cachedNode) {
const name: ?string = getComponentName(cachedNode.componentOptions)
if (name && !filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode)
}
}
}
}
/**
* 修剪缓存入口
*/
function pruneCacheEntry (
cache: VNodeCache,
key: string,
keys: Array<string>,
current?: VNode
) {
const cached = cache[key]
// 主动执行某个组件的destory,触发destroy钩子,达到销毁目的,然后移除缓存中的key-value
if (cached && (!current || cached.tag !== current.tag)) {
cached.componentInstance.$destroy()
}
cache[key] = null
remove(keys, key)
}
const patternTypes: Array<Function> = [String, RegExp, Array]
export default {
name: 'keep-alive',
// 抽象组件,判断当前组件虚拟dom是否渲染成真实dom的关键
abstract: true,
// 定义include、exclude及max属性
// include - 字符串或正则表达式。只有名称匹配的组件会被缓存。
// exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。
// max - 数字。最多可以缓存多少组件实例。
props: {
include: patternTypes,
exclude: patternTypes,
max: [String, Number]
},
created () {
// 组件创建时创建缓存对象
this.cache = Object.create(null) // 缓存虚拟dom
this.keys = [] // 缓存的虚拟dom的键集合
},
destroyed () {
// 销毁时清除所有缓存
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys)
}
},
mounted () {
// 监听include和exclue,使其支持双向绑定。对include和exclude参数进行监听,然后实时地更新(删除)this.cache对象数据
this.$watch('include', val => {
pruneCache(this, name => matches(val, name))
})
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
},
render () {
// $slots.default表示slot中的所有子组件(包括换行)
const slot = this.$slots.default
// 获取第一个组件(这就是为什么keep-alive中只允许渲染一个直属子组件,而不能用v-for的原因)
const vnode: VNode = getFirstComponentChild(slot)
const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
if (componentOptions) {
// 获取子组件名称
const name: ?string = getComponentName(componentOptions)
// 验证组件名称的name是否包含在include或者不在exclude中
const { include, exclude } = this
if (
// not included
(include && (!name || !matches(include, name))) ||
// excluded
(exclude && name && matches(exclude, name))
) {
// 不通过缓存获取,直接加载组件
return vnode
}
const { cache, keys } = this
// 获取key值
const key: ?string = vnode.key == null
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key,
// 如果key队友的vnode存在,则更新key值
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance
// make current key freshest
remove(keys, key)
keys.push(key) // 调整key排序
} else {
// 否则将vnode存入缓存
cache[key] = vnode
keys.push(key)
// 如果超出max则将第一个缓存的vnode移除
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}
vnode.data.keepAlive = true
}
return vnode || (slot && slot[0])
}
}
渲染
Vue的渲染是从图中render阶段开始的,但keep-alive的渲染是在patch阶段,这是构建组件树(虚拟DOM树),并将VNode转换成真正DOM节点的过程。
import App from ‘./App.vue’
new Vue({
render: h => h(App)
}).$mount(’#app’)
- Vue在渲染的时候先调用原型上的_render函数将组件对象转化成一个VNode实例;而_render是通过调用createElement和createEmptyVNode两个函数进行转化;
- createElement的转化过程会根据不同的情形选择new VNode或者调用createComponent函数做VNode实例化;
- 完成VNode实例化后,这时候Vue调用原型上的_update函数把VNode渲染成真实DOM,这个过程又是通过调用patch函数完成的(这就是patch阶段了)
keep-alive组件的渲染
Vue在初始化生命周期的时候,为组件实例建立父子关系会根据abstract属性决定是否忽略某个组件。在keep-alive中,设置了abstract:true,那Vue就会跳过该组件实例。
最后构建的组件树中就不会包含keep-alive组件,那么由组件树渲染成的DOM树自然也不会有keep-alive相关的节点了
export function initLifecycle (vm: Component) {
const options= vm.$options
// 找到第一个非abstract父组件实例
let parent = options.parent
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent
}
parent.$children.push(vm)
}
vm.$parent = parent//将keep-alive的parent 赋给child作为child的parent
跳过keep-alive
// ...
}
keep-alive组件使用缓存
在首次加载被包裹组建时,由keep-alive.js中的render函数可知,vnode.componentInstance的值是undfined,keepAlive的值是true,因为keep-alive组件作为父组件,它的render函数会先于被包裹组件执行;那么只执行到i(vnode,false),后面的逻辑不执行;
再次访问被包裹组件时,vnode.componentInstance的值就是已经缓存的组件实例,那么会执行insert(parentElm, vnode.elm, refElm)逻辑,这样就直接把上一次的DOM插入到父元素中。
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
let i = vnode.data
if (isDef(i)) {
const isReactivated = isDef(vnode.componentInstance) && i.keepAlive
if (isDef(i = i.hook) && isDef(i = i.init)) {
i(vnode, false)
}
if (isDef(vnode.componentInstance)) {
initComponent(vnode, insertedVnodeQueue)
insert(parentElem, vnode.elem, refElem) // 将缓存的DOM(vnode.elem) 插入父元素中
if (isTrue(isReactivated)) {
reactivateComponent(vnode, insertedVnodeQueue, parentEle, refElm)
}
return true
}
}
}
钩子函数
一般的组件,每一次加载都会有完整的生命周期,即生命周期里面对于的钩子函数都会被触发,为什么被keep-alive包裹的组件却不是呢?
被缓存的组件实例会为其设置keepAlive= true,不再进入$mount过程,那mounted之前的所有钩子函数(beforeCreate、created、mounted)都不再执行。
// src/core/vdom/create-component.js
const componentVNodeHooks = {
init (vnode: VNodeWithData, hydrating: boolean): ?boolean{
if (
vnode.componentInstance &&
!vnode.componentInstance._isDestroyed &&
vnode.data.keepAlive
) {
// keep-alive components, treat as a patch
const mountedNode:any = vnode
componentVNodeHooks.prepatch(mountedNode, mountedNode)
} else {
const child = vnode.componentInstance = createComponentInstanceForVnode (vnode, activeInstance)
}
}
}
可重复的activated
在patch的阶段,最后会执行invokeInsertHook函数,而这个函数就是去调用组件实例(VNode)自身的insert钩子:
// src/core/vdom/patch.js
function invokeInsertHook (vnode, queue, initial) {
if (isTrue(initial) && isDef(vnode.parent)) {
vnode.parent.data,pendingInsert = queue
} else {
for(let i =0; i<queue.length; ++i) {
queue[i].data.hook.insert(queue[i]) // 调用VNode自身的insert钩子函数
}
}
}
insert钩子:
const componentVNodeHooks = {
// init()
insert (vnode: MountedComponentVNode) {
const { context, componentInstance } = vnode
if (!componentInstance._isMounted) {
componentInstance._isMounted = true
callHook(componentInstance, 'mounted')
}
if (vnode.data.keepAlive) {
if (context._isMounted) {
queueActivatedComponent(componentInstance)
} else {
activateChildComponent(componentInstance, true/* direct */)
}
}
// ...
}
}
在这个钩子里面,调用了activateChildComponent函数递归地去执行所有子组件的activated钩子函数:
// src/core/instance/lifecycle.js
export function activateChildComponent (vm: Component, direct?: boolean) {
if (direct) {
vm._directInactive = false
if (isInInactiveTree(vm)) {
return
}
} else if (vm._directInactive) {
return
}
if (vm._inactive || vm._inactive === null) {
vm._inactive = false
for (let i = 0; i < vm.$children.length; i++) {
activateChildComponent(vm.$children[i])
}
callHook(vm, 'activated')
}
}
相反地,deactivated钩子函数也是一样的原理,在组件实例(VNode)的destroy钩子函数中调用deactivateChildComponent函数。
参考
https://blog.csdn.net/weixin_33893473/article/details/90884612
https://www.jianshu.com/p/0dcec2254e14