理解keep-alive
keep-alive
是Vue提供的一个抽象组件,用来对组件进行缓存,从而节省性能,由于是一个抽象组件,所以在页面渲染完毕后不会被渲染成一个DOM元素
keep-alive的作用
-
在
vue
项目中难免会有列表页面或搜索结果列表页面,点击某个结果之后,返回回来这个页面时还是之前的搜索结果的列表 -
在
router-view
上使用可以缓存该路由组件 -
有两个参数 Props:
include
字符串或正则表达式,只有匹配组件会被缓存exclude
字符串或正则表达式,任何匹配的组件都不会被缓存
使用场景
- Vue中前进刷新,后退缓存用户浏览数据\
- 列表页面 =>点击进入详情页=> 后退到列表页 要缓存列表原来数据
- 重新进入列表页面 => 获取最新的数据
使用方法
缓存动态组件
包裹动态组件时,会缓存不活动的组件实例,而不是销毁
<keep-alive>
<component :is='view'></component>
</keep-alive>
缓存路由组件
使用keep-alive 可以将所有路径匹配到的路由组件都缓存起来,包括组件里面的组件
<keep-alive>
<router-view></router-view>
</keep-alive>
生命周期函数
activated
- 组件激活时使用
- 在服务端渲染期间不被调用
deactivated
- 在
keep-alive
组件中停用时调用 - 在服务端渲染期间不被调用
- 被包含在
keep-alive
中创建的组件,会多出两个生命周期的钩子:activated
与deactivated
- 使用
keep-alive
会将数据保留在内存中,如果要在每次进入页面的时候获取最新的数据,需要在activated
阶段获取数据,承担原来created
钩子函数中获取数据的任务
源码解析
/**
* 引用工具函数:
* isRegExp : 判断是否是正则表达式
* remove: 从数组中删除某一项
* getFirstComponentChild:
*/
import { isRegExp, remove } from 'shared/util'
import { getFirstComponentChild } from 'core/vdom/helpers/index'
/**
* 开始以为是typescript类型,但是发现两点疑问:
* 1.文件不是ts后缀
* 2.:和?的顺序不对
* 结论:原来这家伙是基于FLOW去做的类型检查,有兴趣的同学自行了解一下
* 表示引用一个复杂类型,[]表示可以通过key进行索引,?表示值的类型是可选的
* 其实第一个行有个注释 @flow,开始没看到~~
*/
type VNodeCache = { [key: string]: ?VNode };
function getComponentName (opts: ?VNodeComponentOptions): ?string {
// 获取组件名称:如果option中有定义name属性则直接返回否则返回tag
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)
}
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',
// 抽象组件
abstract: true,
// 定义include、exclude及max属性
// include - 字符串或正则表达式。只有名称匹配的组件会被缓存。
// exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。
// max - 数字。最多可以缓存多少组件实例。
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 () {
// 监听include和exclue,使其支持双向绑定
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])
}
}
小结
<keep-alive>
是一个抽象组件
- 首次渲染的时候设置缓存
- 缓存渲染的时候不会执行组件的created、mounted等钩子函数,而是对缓存的组件执行 matches 过程,最后直接更新到目标元素。
使用LUR缓存策略(缓存淘汰策略)对组件进行缓存
- 命中缓存,则直接返回缓存,同时更新缓存key的位置
- 不命中缓存则设置进缓存,同时检查缓存的实例数量是否超过max