keep-alive之源码解读

198 阅读3分钟

keep-alive是什么

keep-alive是一个抽象组件:它自身不会渲染一个DOM元素,也不会出现在父组件链中;使用keep-alive包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。(配合LRU算法使用)

主要是有include、exclude、max三个属性;前两个属性允许keep-alive有条件的进行缓存;max可以定义组件最大的缓存个数,如果超过了这个个数的话,在下一个新实例创建之前,就会将以缓存组件中最久没有被访问到的实例销毁掉。

LRU算法介绍

LRU的全称为Least Recently Used。它是一种内存淘汰算法,当内存不够时,将内存中最久没使用的数据清理掉。LRU算法常用于缓存的淘汰策略。

LRU算法原理

为了更好地描述和理解LRU算法的原理,此处我们以一个队列举例,队列的头部表示最久没有被访问的数据,队列的尾部表示最近刚访问的数据。假如定义一个长度为4的队列,我们随意添加几个数据进去,如下图:

LRU.png

此时,我们访问一次下标为1的元素,根据LRU算法的思想,需要将下标为1的元素移动到队列的尾部,表示该元素最近访问过,后面的元素依次前移,如下图:

)5@9RNA2GDU34J}(VOD1AQA.png

此时,我们再向队列中添加一个元素,由于队列已经满了,所以我们需要将队列头部(最久没有访问)的元素移除掉,然后将后面的元素依次前移,最后将新的元素添加到队列的尾部,如下图:

LRU1.png

这样,每次队列满了的时候添加新的元素,我们只需要将队列头部的元素移除掉即可,这样就达到了淘汰最近最少使用数据的功能,这就是LRU算法的基本原理。

keep-alive源码


import { isRegExp, remove } from 'shared/util'
import { getFirstComponentChild } from 'core/vdom/helpers/index'

type CacheEntry = {
  name: ?string;
  tag: ?string;
  componentInstance: Component;
};

type CacheEntryMap = { [key: string]: ?CacheEntry };

// 获取组件的名称
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
}


/**
 * 修正缓存
 */
function pruneCache (keepAliveInstance: any, filter: Function) {
  // 当前 keep-alive 实例  缓存 key 数组 当前虚拟NODE
  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)
}

const patternTypes: Array<Function> = [String, RegExp, Array]

export default {
  name: 'keep-alive',
  abstract: true, // 提取组件

  props: {
    include: patternTypes, // 包含
    exclude: patternTypes, // 不包含
    max: [String, Number] // 最大缓存数
  },

  methods: {
    cacheVNode() {
      // {} []  VNode key
      const { cache, keys, vnodeToCache, keyToCache } = this
      if (vnodeToCache) {
        const { tag, componentInstance, componentOptions } = vnodeToCache
        // 把当前缓存的对象挂到 cache 对象 
        cache[keyToCache] = {
          name: getComponentName(componentOptions),
          tag,
          componentInstance,
        }
        // 把 key 添加到缓存 keys 数组里
        keys.push(keyToCache)
        // prune oldest entry
        // 最大缓存数  keys 长度 大于 最大缓存数
        // LRU 缓存淘汰算法
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
        // 清除 vnodeToCache 这个变量
        this.vnodeToCache = null
      }
    }
  },
  // 创建缓存表
  created () {
    this.cache = Object.create(null) // {}
    this.keys = [] // []
  },
  //组件销毁后
  destroyed () {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },
  //组件挂载后
  mounted () {
    this.cacheVNode()
    this.$watch('include', val => {
      pruneCache(this, name => matches(val, name))
    })
    this.$watch('exclude', val => {
      pruneCache(this, name => !matches(val, name))
    })
  },
  //组件更新
  updated () {
    this.cacheVNode()
  },
  
  render () {
    // 获取插槽的默认元素 this.$slots
    const slot = this.$slots.default
    // 获取第一个缓存的组件
    const vnode: VNode = getFirstComponentChild(slot)
    // 拿出当前组件的 options 选项
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      // check pattern

      // 获取组件名称
      const name: ?string = getComponentName(componentOptions)

      // 获取组件传过来的 props 包含 未包含
      const { include, exclude } = this
      if (
        // not included
        (include && (!name || !matches(include, name))) ||
        // excluded
        (exclude && name && matches(exclude, name))
      ) {
      // 不匹配,直接返回组件实例(`VNode`),否则开启缓存策略。
        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
         // LRU 缓存淘汰算法
        remove(keys, key)
        keys.push(key)
      } else {
        // delay setting the cache until update
        // 缓存当前的组件实例
        this.vnodeToCache = vnode
        // 缓存当前组件的 key
        this.keyToCache = key
      }
      // 最后将该组件实例的keepAlive属性值设置为true。
      vnode.data.keepAlive = true
    }
    // 返回组件实例 返回插槽第一个元素
    return vnode || (slot && slot[0])
  }
}