keep-alive解析

174 阅读3分钟

keep-alive是什么

keep-alive就是保持组件活跃,不会被destroy销毁掉,就一直还活着,组件没有被销毁掉的话,组件上挂载的数据就还存在,所以状态就可以保留,所以,keep-alive就可以保持组件的状态。

include和exclude指定是否缓存某些组件

include属性

include 包含的意思。值为字符串或正则表达式或数组。只有组件的名称与include的值相同的才会被缓存,即指定哪些被缓存,可以指定多个被缓存。这里以字符串为例,指定多个组件缓存,语法是用逗号隔开。如下:

// 指定home组件和about组件被缓存
<keep-alive include="home,about" >
    <router-view></router-view>
</keep-alive>

exclude属性

exclude相当于include的反义词,就是除了的意思,指定哪些组件不被缓存,用法和include类似,如下:

// 除了home组件和about组件别的都缓存,本例中就是只缓存detail组件
<keep-alive exclude="home,about" >
    <router-view></router-view>
</keep-alive>

include和exclude的属性值是组件的名称

include和exclude的属性值是组件的名称,也就是组件的name属性值,也就是如下的name属性值。

<script>
    export default {
      name: "App"
      // ...
    };
</script>

用法

 <!-- 路由导航对应的内容区 -->
    <main>
      <keep-alive> <!-- 使用keep-alive包了一层,就可以缓存啦 -->
        <router-view></router-view>
      </keep-alive>
    </main>
  </div>

keep-alive 原理

keep-alive中运用了LRU(Least Recently Used)算法。

  1. 获取 keep-alive 包裹着的第一个子组件对象及其组件名; 如果 keep-alive 存在多个子元素,keep-alive 要求同时只有一个子元素被渲染。所以在开头会获取插槽内的子元素,调用 getFirstComponentChild 获取到第一个子元素的 VNode
  2. 根据设定的黑白名单(如果有)进行条件匹配,决定是否缓存。不匹配,直接返回组件实例(VNode),否则开启缓存策略。
  3. 根据组件ID和tag生成缓存Key,并在缓存对象中查找是否已缓存过该组件实例。如果存在,直接取出缓存值并更新该key在this.keys中的位置(更新key的位置是实现LRU置换策略的关键)。
  4. 如果不存在,则在this.cache对象中存储该组件实例并保存key值,之后检查缓存的实例数量是否超过max设置值,超过则根据LRU置换策略删除最近最久未使用的实例(即是下标为0的那个key)。最后将该组件实例的keepAlive属性值设置为true
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))
      ) {
        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
      }

      vnode.data.keepAlive = true
    }
    // 返回组件实例 返回插槽第一个元素
    return vnode || (slot && slot[0])
  }
}