keep-alive原理

keep-alive

组件复用,提高性能
缓存不太使用的组件,而不是直接销毁

参数

  1. include: [String,RegExp,Array] 只有匹配到的组件才能进行缓存
  2. exclude:[String,RegExp,Array] 匹配到的组件都不缓存
  3. max: [String,Number] 数字,最多能缓存多少组件实例。在新实例创建之前,缓存中最就没有使用的实例会被销毁

props:三个属性 include exclude max

created:定义两个属性

this.cache = Object.create(null)
this.keys = []

this.cache是一个对象,用来存储需要缓存的组件

this.cache = {
    'key1':'组件1',
    'key2':'组件2'
    、、、
}

this.keys是以一个数组,用来存储每个需要缓存的组件的key,即对应this.cache对象中的键值。

destoryed

该钩子会遍历this.cache对象,然后将那些被缓存的并且当前没有处于被渲染状态的组件都销毁掉,并将其从this.cache对象中移除

destoryed() {
    for (const key in this.cache) {
        pruneCacheEntery(this.cache,key,this.keys);
    }
}

function pruneCacheEntery(cache,key,keys,current) {
    const cached = cache[key]
    if (cached &&& (!current || cached.tag !== current.tag)) {
        cached.componentInstance.$destory()
    }
    cache[key] = null
    remove(keys,key)
}

mounted

在mounted中观测 include exclude的变化

mounted () {
    this.$watch('include', val => {
        pruneCache(this, name => matches(val,name))
    })
    this.$watch('exclude', val => {
        pruneCache(this, name => !matches(val,name))
    })
}

render

keep-alive如何实现缓存

  1. 获取第一个子组件的节点
const slot = this.$solts.default
const vnode = getFirstComponentChild(solt)

只处理第一个子元素,所以一般和它搭配使用的有 component 动态组件或者是 router-view。

  1. 获取该组件节点的名称
/* 获取该组件节点的名称 */
const name = getComponentName(componentOptions)

/* 优先获取组件的name字段,如果name不存在则获取组件的tag */
function getComponentName (opts: ?VNodeComponentOptions): ?string {
  return opts && (opts.Ctor.options.name || opts.tag)
}
  1. 用组件名称跟include exclude 中的普配规则取匹配
  • 如果name与index规则不匹配或者与exclude规则匹配,表示不缓存该组件,直接返回这个组件的vnode就可以
const { include, exclude } = this
if (
    (include && (!name || !matches(include, name))) ||
    (exclude && name && !matches(exclude,name))
) {
    return vnode
}
  • 否则进行缓存
const { cache, keys } = this
// 获取组件的key值
const key = vnode.key == null?
componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key

//拿到key值后取this.cach对象中寻找是否有该值,如果有,说明组件有缓存,命中缓存
/* 如果命中缓存,则直接从缓存中拿 vnode 的组件实例 */
if (cache[key]) {
    vnode.componentInstance = cache[key].componentInstance
    /* 调整该组件key的顺序,将其从原来的地方删掉并重新放在最后一个 */
    remove(keys, key)
    keys.push(key)
} else {
    cache[key] = vnode
    keys.push(key)
    /* 如果配置了max并且缓存的长度超过了this.max,则从缓存中删除第一个 */
    if (this.max && keys.length > parseInt(this.max)) {
        pruneCacheEntry(cache, keys[0], keys, this._vnode)
    }
}
// 如果没有,则将组件存入缓存

LRU 最近最少使用

当使用keep-alive后,组件将不会进行created和mounted,但是有的时候我们需要在组件里面执行一定的操作,用的是activated和deactivated 两个钩子函数,它的执行时机是 包裹的组件激活时调用和停用时调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值