keep-alive源码解析,如何实现缓存的

84 阅读3分钟

认识keep-alive

在了解keep-alive之前,我们需要先知道keep-alive是做什么的!我们所知道的,在性能优化上,最常见的手段就是缓存。对需要经常访问的资源进行缓存,减少请求或者是初始化的过程,从而降低时间或内存的消耗。Vue为我们提供了缓存组件 keep-alive,它可用于路由级别或组件级别的缓存。

LRU策略

在解析keep-alive之前我们需要先了解一下LRU策略。

那什么是LRU策略呢?

LRU策略根据数据的历史访问记录来进行淘汰数据。LRU 策略的设计原则是,如果一个数据在最近一段时间没有被访问到,那么在将来它被访问的可能性也很小。也就是说,当限定的空间已存满数据时,应当把最久没有被访问到的数据淘汰。

v2-998b52e7534278b364e439bbeaf61d5e_720w.png

源码解析

知道了什么是LRU 我们再来分析一下keep-alive的源码

props

{
props: 
    include: patternTypes,
    exclude: patternTypes,
    max: [String, Number]
  },
  
  1. include定义缓存白名单,keep-alive会缓存命中的组件;
  2. exclude定义缓存黑名单,被命中的组件将不会被缓存;
  3. max定义缓存组件上限,超出上限使用LRU的策略置换缓存数据;

created

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

created方法就很简单了,他只初始化了两个变量

  1. cache用来缓存虚拟dom;
  2. keys用来缓存虚拟dom的键集合

mounted

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

在mounted这个钩子中对include和exclude参数进行监听,然后实时地更新this.cache对象数据。pruneCache函数的核心也是去调用pruneCacheEntry。

render

 render () {
    const slot = this.$slots.default
    const vnode: VNode = getFirstComponentChild(slot)
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      // check pattern
      const name: ?string = 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: ?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)
        keys.push(key)
      } else {
        // delay setting the cache until update
        this.vnodeToCache = vnode
        this.keyToCache = key
      }

      vnode.data.keepAlive = true
    }
    return vnode || (slot && slot[0])
  }
  1. 获取keep-alive包裹着的第一个子组件对象及其组件名;

  2. 根据设定的黑白名单(如果有)进行条件匹配,决定是否缓存。不匹配,直接返回组件实例(VNode),否则执行第三步;

  3. 根据组件ID和tag生成缓存Key,并在缓存对象中查找是否已缓存过该组件实例。如果存在,直接取出缓存值并更新该key在this.keys中的位置(更新key的位置是实现LRU置换策略的关键),否则执行第四步;

  4. 在this.cache对象中存储该组件实例并保存key值,之后检查缓存的实例数量是否超过max的设置值,超过则根据LRU置换策略删除最近最久未使用的实例(即是下标为0的那个key);

  5. 最后将该组件实例的keepAlive属性值设置为true;

destroyed

destroyed () {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },
function pruneCacheEntry (
  cache: CacheEntryMap,
  key: string,
  keys: Array<string>,
  current?: VNode
) {
  const entry: ?CacheEntry = cache[key]
  if (entry && (!current || entry.tag !== current.tag)) {
    entry.componentInstance.$destroy()
  }
  cache[key] = null
  remove(keys, key)
}
  1. this.cache中缓存的VNode实例;
  2. 遍历调用pruneCacheEntry函数删除缓存VNode还要对应执行组件实例的destory函数;

接下来我们看看keep-alive封装的方法

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
}

在这个方法中我们判断配置和当前组件名称是否匹配

function pruneCache (keepAliveInstance: any, filter: Function) {
  const { cache, keys, _vnode } = keepAliveInstance
  for (const key in cache) {
    const entry: ?CacheEntry = cache[key]
    if (entry) {
      const name: ?string = entry.name
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

匹配条件同时清除缓存

function pruneCacheEntry (
 cache: CacheEntryMap,
 key: string,
 keys: Array<string>,
 current?: VNode
) {
 const entry: ?CacheEntry = cache[key]
 if (entry && (!current || entry.tag !== current.tag)) {
   entry.componentInstance.$destroy()
 }
 cache[key] = null
 remove(keys, key)
}

创建缓存对象和保存组件key

以上就是keep-alive所有源码

总结

大致的缓存流程,vue有个内置组件、这个组件维护着缓存对象和被缓存组件的key名称、提高你传入的include, exclude判断是否需要缓存当前组件、而且我们在render函数发现组件永远都只会取第一个子组件内容、而我们案例上的demo组件永远没有机会显示出来、其实也有办法那就是给他们包裹vue提供的另外一个内置组件component、判断显示那个组件、然后keep-alive会提高当前组件是否设置了白名单或者不是include配置项组件那就直接return vnode,遇到缓存的vnode、先判断缓存对象是否已经存如果存在直接取缓存vnode (有个小细节、重新调整组件key的位置、目的是为了如果数据最近被访问过,那么将来被访问的几率也更高、因为可能缓存到一定max数量、会遇到删除栈的vnode、这个时候是根据key的位置在操作的) 、不存在的话往缓存对象添加记录