Vue学习笔记---keep-alive源码学习

1.使用

<keep-alive>
    <component :is="chooseComponent"></component>
</keep-alive>

2.源码分析

1.props:keep-alive支持配置的属性作为prop传入

props: {
    include: [String, RegExp, Array],//缓存包含组件
    exclude: [String, RegExp, Array],//缓存不包含组件
    max: [String, Number]//最大缓存组件
}

2.created:创建组件缓存数组以及标识数组

created () {
    this.cache = Object.create(null)//缓存组件数组
    this.keys = []//组件数组中元素的标识
}

3.mounted:检测include和exclude的变化,变化规则后的部分组件不需要缓存则从其中剔除

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

function pruneCache (keepAliveInstance, filter) {
  const { cache, keys, _vnode } = keepAliveInstance
  for (const key in cache) {
    const cachedNode = cache[key]
    if (cachedNode) {
      const name = getComponentName(cachedNode.componentOptions)
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

4.render:

  • 获取渲染节点
  • 不符合传入规则不缓存直接渲染
  • 符合规则对该组件进行判断,缓存中存在的调用缓存组件,缓存中不存在的写入缓存,最后再渲染
/* 获取渲染节点 */
const slot = this.$slots.default
const vnode = getFirstComponentChild(slot)

/* 不符合传入规则不缓存直接渲染 */
function getComponentName (opts: ?VNodeComponentOptions): ?string {
   return opts && (opts.Ctor.options.name || opts.tag)
}
const name = getComponentName(componentOptions)
const { include, exclude } = this
if (
    (include && (!name || !matches(include, name))) ||
    (exclude && name && matches(exclude, name))
) {  return vnode  }

/* 符合规则对该组件进行判断,缓存中存在的调用缓存组件,缓存中不存在的写入缓存 */
const { cache, keys } = this
const key = vnode.key == null
? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key

/* 缓存中存在的调用缓存组件 */
if (cache[key]) {
    vnode.componentInstance = cache[key].componentInstance
    // 移除原来的可以将其放到最后一个,便于引用缓存淘汰策略
    remove(keys, key)
    keys.push(key)
}
/* 缓存中不存在的写入缓存 */
else {
    cache[key] = vnode
    keys.push(key)
    // 执行
    if (this.max && keys.length > parseInt(this.max)) {
        pruneCacheEntry(cache, keys[0], keys, this._vnode)
    }
}
/* 最后设置keepAlive标记位 */
vnode.data.keepAlive = true

5.destroyed:将那些被缓存的并且当前没有处于被渲染状态的组件都销毁掉并将其从this.cache对象中剔除

destroyed () {
    for (const key in this.cache) {
        pruneCacheEntry(this.cache, key, this.keys)
    }
}

function pruneCacheEntry (cache,key,keys,current) {
  const cached = cache[key]
  /* 判断当前没有处于被渲染状态的组件,将其销毁*/
  if (cached && (!current || cached.tag !== current.tag)) {
    cached.componentInstance.$destroy()
  }
  cache[key] = null
  remove(keys, key)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值