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)
}

你可能感兴趣的:(Vue学习笔记,vue.js,javascript,ecmascript)