Vue 中 Keep-Alive 的源码和原理

65 阅读2分钟

Keep-Alive是什么?

  • keep-alive是vue的内置组件,是用来包裹动态组件的,它会缓存不活跃的组件,keep-alive是一个比较抽象的组件,它自己不会渲染dom节点,也不会出现在父组件链中。

Keep-Alive的功能?

  • 在组件切换过程中 把切换出去的组件保留在内存中,防止重复渲染DOM,减少加载时间及性能消耗,提高用户体验性。

keep-alive的属性exclude

  • 因为我们在做某个项目的时候不希望某个页面一直重复加载加载这时就需要用到exclude(不允许某个组件缓存)这个属性也叫黑名单
    <keep-alive exclude="alive1">
         <component :is="name"></component>
    </keep-alive>

1. 字符串设置(以逗号分隔)

    <keep-alive :exclude="/alive1|alive2/">
        <component :is="name"></component>
    /keep-alive>

2. 正则表达式

    <keep-alive :exclude="/alive1|alive2/">
        <component :is="name"></component>
    </keep-alive>

3. 数组

    <keep-alive :exclude="[alive1,alive2]">
        <component :is="name"></component>
    </keep-alive>

keep-alive的属性include

  • 这个属性和上面的恰恰相反,这个属性意思是只允许某个组件缓存也叫白名单
    <keep-alive include="alive1">
        <component :is="name"></component>
    </keep-alive>

1. 字符串设置(以逗号分隔)

    <keep-alive include="alive1,alive2">
        <component :is="name"></component>
    </keep-alive>

2. 正则表达式

    <keep-alive :include="/alive1|alive2/">
        <component :is="name"></component>
    </keep-alive>

3. 数组

    <keep-alive :indclude="[alive1,alive2]">
        <component :is="name"></component>
    </keep-alive>
  • *数组和正则必须使用v-bind   ‘:’
  • 这样就可以做到某个组件不缓存

keep-alive的属性max

  • 这个属性传递的是number类型,意味着最多可以缓存几个组件;
    <keep-alive :max="10">
        <component :is="name"></component>
    </keep-alive>

代码分析

export default {
  name: 'keep-alive',
  abstract: true, //抽象组件
 
  props: { //接收三个参数
    include: patternTypes,
    exclude: patternTypes,
    max: [String, Number]
  },
 
  created () {
    this.cache = Object.create(null) //缓存的组件
    this.keys = [] //缓存组件的key数组
  },
 
  destroyed () {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys) //删除缓存中所有组件
    }
  },
 
 /**
    监听include和exclude的值,如果当前cache中的组件不在include中或在exclude中,则
    需要将该组件从cache中去掉。pruneCache方法就是将cache中不满足include和exclude
    规则的组件删除掉
 */
  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 //获取keep-alive标签包裹的默认插槽中的元素
    const vnode: VNode = getFirstComponentChild(slot) //获取到默认插槽中的第一个子元素(keep-alive只对第一个子元素起作用)
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      const name: ?string = getComponentName(componentOptions)
      const { include, exclude } = this
      if ( //如果组件不符合include和exclude规则,那么直接返回该组件,不需要从缓存中获取
        (include && (!name || !matches(include, name))) ||
        (exclude && name && matches(exclude, name))
      ) {
        return vnode
      }
 
      const { cache, keys } = this
      const key: ?string = vnode.key == null
        ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
        : vnode.key
      if (cache[key]) { //如果缓存中存在当前组件
        vnode.componentInstance = cache[key].componentInstance //将缓存中的组件实例赋给当前组件实例
        remove(keys, key) //将当前组件key从缓存的keys数组中删除
        keys.push(key) //将当前组件keypush到缓存的keys中,以此来保持该组件在缓存中是最新的
      } else { //如果缓存中没有当前组件
        cache[key] = vnode //将当前组件放入缓存中
        keys.push(key) //将当前组件key放入缓存keys数组中
        if (this.max && keys.length > parseInt(this.max)) { //如果已缓存的组件数量大于max值,则将缓存keys数组中第一个组件删除掉。(缓存中组件的顺序是不常用的在前面,常用的在后面,这是由上面代码中如果组件在缓存中,就需要先在缓存中删除组件key,再重新向缓存keys数组中推入组件key的实现方式决定的)
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
      }
 
      vnode.data.keepAlive = true //标记该组件的keepAlive状态
    }
    return vnode || (slot && slot[0]) //如果上面方法没执行,则直接返回vnode或第一个子元素
  }
}