源码位置
src/components/keep-alive.js
。
逐行分析
// 获取组件的name
function getComponentName (opts: ?VNodeComponentOptions): ?string {
return opts && (opts.Ctor.options.name || opts.tag)
}
// 判断pattern是否能与name匹配上
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
}
// 用来处理当include和exclude属性变化时,清楚cache中不需要缓存的组件实例
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)
}
}
}
}
// 清除cache中keys中的key对应的缓存组件实例
function pruneCacheEntry (
cache: VNodeCache,
key: string,
keys: Array<string>,
current?: VNode
) {
const cached = cache[key]
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',
abstract: true, // 官方没有暴露这个属性,这个为true的话就是在destory的时候不会从它的父级中移除
/**
* 在src/core/instance/lifecycle.js中
* Vue.prototype.$destroy = function() {
* ...
* if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { // 由于abstract为true,所以始终不会把它从父级中移除
* remove(parent.$children, vm) // 将vm从parent.$children中移除
* }
* ...
* }
*/
props: {
include: patternTypes,
exclude: patternTypes,
max: [String, Number]
},
created () {
this.cache = Object.create(null)
this.keys = []
},
destroyed () { // keepa-live组件卸载时,移除所有的组件实例缓存
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys)
}
},
mounted () { // 加载的时候,开启监听include和exclude的变化去动态清理不需要缓存的组件
this.$watch('include', val => {
pruneCache(this, name => matches(val, name))
})
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
},
render () {
const slot = this.$slots.default // 拿到slot
const vnode: VNode = getFirstComponentChild(slot) // 获取插槽下的第一个子节点
const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions // 获取子组件的组件配置项信息
if (componentOptions) {
// check pattern
const name: ?string = getComponentName(componentOptions) // 获取组件的name
const { include, exclude } = this
// 判断该组件是否需要被缓存,不需要就直接返回该vnode
if (
// not included
(include && (!name || !matches(include, name))) ||
// excluded
(exclude && name && matches(exclude, name))
) {
return vnode
}
// 走到这里需要被缓存了
const { cache, keys } = this
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
// 先判断当前缓存中是否存在对应的实例,如果有就将缓存的实例赋值给当前实例
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance
// make current key freshest
// 这一步看起来很无聊,实际是为了把最新缓存的组件放到缓存的顶部,因为它内部会有一个缓存的组件最大数量的,当缓存到了极限就会把缓存的底部的一条数据清掉
remove(keys, key)
keys.push(key)
} else {
// 没有当前实例,就把实例放进缓存中
cache[key] = vnode
keys.push(key)
// prune oldest entry,这一步就是用来判断是否到达了最大储存限制,超过了就删掉第一个储存的组件实例
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}
// 给虚拟dom的数据的keepAlive设置为true
vnode.data.keepAlive = true
}
return vnode || (slot && slot[0]) // 返回缓存中的vnode
}
}
小结
keep-alive
由于使用了abstract
属性,导致本身在触发destory
方法时不会从父级中被卸载掉,所以可以通过其本身来缓存它的子组件。这也是我目前的一点粗鄙的见解,后面再看到相关的更详细内容会进行补充。