vue的<keep-alive>主要是对组件进行缓存,在跳转到其他页面再跳回来时组件还是一样的状态,避免组件重新渲染,它是一个抽象组件,不会渲染到页面。下面来看下应用
//index.js
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path:'/test',
name:"Test",
component:Test
}
]
})
//App.vue
<template>
<div id="app">
<img src="./assets/logo.png">
<keep-alive include="Test" exclude="HelloWorld">
<router-view/>
</keep-alive>
</div>
</template>
//Test.vue
<template>
<div>
<input type="text">
<router-link to="/">跳转</router-link>
</div>
</template>
//HelloWorld.vue
<template>
<div class="hello">
<input type='text'>
<router-link to='/test'>跳转</router-link>
</div>
</template>
<keep-alive></keep-alive>有三个值,默认是所有组件都被缓存,exclude的值是不需要被缓存的组件的名称,include是需要被缓存的组件的名称.exclude的优先级要大于include,它还有两个周期函数activated和deactivated,分别是在缓存组件的mounted生命周期之后和跳转到其他页面时触发,除此之外,它还有一个max值,规定了最多可以缓存多少组件。看了下源码,大概的意思就是将include缓存的组件放在一个数组中,当数组的长度大于max值时,他会移除最新进入这个数组的组件,然后再把当前要缓存的组件插入到数组中,如果当前组件已经在数组中,则把它移至数组的末尾
function getComponentName (opts: ?VNodeComponentOptions): ?string {
//获取组件的name值或tag值
return opts && (opts.Ctor.options.name || opts.tag)
}
function matches (pattern: string | RegExp | Array<string>, name: string): boolean {
//比较当前组件的name值和include值
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]//缓存的组件和当前的组件不一样
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,
props: {
include: patternTypes,
exclude: patternTypes,
max: [String, Number]
},
created () {
this.cache = Object.create(null)
this.keys = []//创建缓存的组件数组
},
destroyed () {
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys)
}
},
mounted () {
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
const vnode: VNode = getFirstComponentChild(slot)
const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
if (componentOptions) {
// check pattern
const name: ?string = getComponentName(componentOptions)
const { include, exclude } = this
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
//判断缓存组件数量是否大于max值
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}
vnode.data.keepAlive = true
}
return vnode || (slot && slot[0])
}
}