keep-alive的源码解析

keep-alive的源码解析

概念

​ keep-alive是一个vue内置组件,但是是一个抽象组件,不会出现在父组件链中,也不会在DOM中渲染

原理

​ 在组件的created函数中初始话caches数组和keys数组用来存储需要缓存的组件和组件的key值

  created() {
    this.cache = Object.create(null)
    this.keys = []
  },

​ 在render函数中:
​ 首先获取写在组件默认插槽中的第一个组件(获取到的是一个vnode???按照源码是vnode)
​ 然后获取组件的componentOptions属性,再从中获取组件的名字(name/tagName)
​ 如果没有name或着name值不在include中或者name值在黑名单中,就直接返回该vnode
​ 如果有name值并且包含在includes中,就获取组件的key值
​ 再根据key值判断是否已经缓存了该组件

如果缓存了就给vnode的componentInstance属性赋值缓存中的该组件的componentInstance值
​ 然后移除keys数组中的当前key值,在重新插入当前key值在最后,因为可能出现缓存的组件数量大于max值的情况,需要从前面删除已经缓存的组件(思想类似于LRU算法,最近最久未使用更新)

​ 如果还没缓存就执行 this.vnodeToCache = vnode,this.keyToCache = key,这一步为了在cacheVNode判断是否需要缓存组件,最后返回修改后的vnode节点

 render() {
    const slot = this.$slots.default
    const vnode = getFirstComponentChild(slot)//获取第一个组件
    const componentOptions = vnode && vnode.componentOptions//获取该组件的属性值
    if (componentOptions) {
      // check pattern
      const name = _getComponentName(componentOptions)//获取组件名
      const { include, exclude } = this
      if (
        // not included
        (include && (!name || !matches(include, name))) ||//获取不到组件名或组件名不在白名单
        // excluded
        (exclude && name && matches(exclude, name))//组件名在黑名单
      ) {
        return vnode
      }

      const { cache, keys } = this
      const key =
        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
      if (cache[key]) {//如果已经缓存过该组件
        vnode.componentInstance = cache[key].componentInstance//直接获取该组件缓存渲染
        // make current key freshest
        remove(keys, key)
        keys.push(key)
      } else {//如果还没缓存该组件
        // delay setting the cache until update
        this.vnodeToCache = vnode
        this.keyToCache = key
      }

      // @ts-expect-error can vnode.data can be undefined
      vnode.data.keepAlive = true
    }
    return vnode || (slot && slot[0])
  }
}

然后就会执行mounted函数,在mounted函数中会调用了cacheVNode函数和watch了includes和excludes

  mounted() {
    this.cacheVNode()
    this.$watch('include', val => {
      pruneCache(this, name => matches(val, name))//match函数是用来判断name值是否存在在val中
    })
    this.$watch('exclude', val => {//pruneCache函数用来移除缓存中的组件
      pruneCache(this, name => !matches(val, name))
    })
  },

在cacheVNode函数中(cacheVNode函数会在mounted和updated钩子函数中被调用),首先判断vnodeToCache是否有值,如果有值就说明当前获取到的组件是第一次进入且需要被缓存,就做缓存操作,分别在caches中和keys中插入组件实例和key值,然后还需要判断当前缓存的组件的数量是否超过了max值,如果超过了就需要从前面删除已经缓存的组件,完成后再把vnodeToCache置为null,表示组件缓存完毕,防止下一次再进入该函数后做了不必要的操作

    cacheVNode() {
      const { cache, keys, vnodeToCache, keyToCache } = this
      if (vnodeToCache) {//判断是否需要缓存组件
        const { tag, componentInstance, componentOptions } = vnodeToCache
        cache[keyToCache] = {//缓存组件
          name: _getComponentName(componentOptions),
          tag,
          componentInstance
        }
        keys.push(keyToCache)
        // prune oldest entry
        if (this.max && keys.length > parseInt(this.max)) {//判断当前缓存的数量是否大于max
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
        this.vnodeToCache = null
      }
    }
  },

最后在destoty钩子函数中清除缓存的所有组件

  destroyed() {
    for (const key in this.cache) {
      //清除所有已缓存的组件
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },

附完整代码(源代码及注释转载自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) {
      // check pattern
      const name: ?string = getComponentName(componentOptions)
      const { include, exclude } = this
      if ( //如果组件不符合include和exclude规则,那么直接返回该组件,不需要从缓存中获取
        // not included
        (include && (!name || !matches(include, name))) ||
        // excluded
        (exclude && name && matches(exclude, name))
      ) {
        return vnode
      }
 
      const { cache, keys } = this
      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
      if (cache[key]) { //如果缓存中存在当前组件
        vnode.componentInstance = cache[key].componentInstance //将缓存中的组件实例赋给当前组件实例
        // make current key freshest
        remove(keys, key) //将当前组件key从缓存的keys数组中删除
        keys.push(key) //将当前组件keypush到缓存的keys中,以此来保持该组件在缓存中是最新的
      } else { //如果缓存中没有当前组件
        cache[key] = vnode //将当前组件放入缓存中
        keys.push(key) //将当前组件key放入缓存keys数组中
        // prune oldest entry
        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或第一个子元素
  }
}


/**
* 获取组件的名称。组件的componentOptions包含以下几个属性{ Ctor, tag, propsData, listeners,children } ,通过Ctor.options.name或tag可以获取到组件的name值
**/
function getComponentName (opts: ?VNodeComponentOptions): ?string {
  return opts && (opts.Ctor.options.name || opts.tag)
}
/**
* 判断组件是否在include或exclude中
**/
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)
  }
  /* istanbul ignore next */
  return false
}
 
/**
* 如果缓存的组件不在include或exclude的规则内,则将组件从缓存中删除
*/
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]
  if (cached && (!current || cached.tag !== current.tag)) {
    cached.componentInstance.$destroy()
  }
  cache[key] = null
  remove(keys, key)
}

你可能感兴趣的:(源码,原理,vue.js,javascript,前端)