vue2 keep-alive&源码

122 阅读3分钟

keep-alive

keep-alive 是 vue 中的内置组件,使用 KeepAlive(它自身不会渲染一个 DOM 元素) 后,被包裹的组件在经过第一次渲染后的 vnode 会被缓存起来,然后再下一次再次渲染该组件的时候,直接从缓存中拿到对应的 vnode 进行渲染,并不需要再走一次组件初始化,render 和 patch 等一系列流程,减少了 script 的执行时间,性能更好。

参数及用法

  • include:可传字符串、正则表达式、数组,名称匹配成功的组件会被缓存
  • exclude:可传字符串、正则表达式、数组,名称匹配成功的组件不会被缓存
  • max    :可传数字,限制缓存组件的最大数量,超过max则按照LRU算法进行置换

用法

<!-- 用逗号分隔的字符串 -->
<KeepAlive include="a,b">
<component :is="view"></component>
</KeepAlive>
<!-- 正则表达式 (使用 `v-bind`) -->
<KeepAlive :include="/a|b/">
<component :is="view"></component>
</KeepAlive>
<!-- 数组 (使用 `v-bind`) -->
<KeepAlive :include="['a', 'b']">
<component :is="view"></component>
</KeepAlive>

activated & deactivated

当组件在 <keep-alive> 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。

image.png image.png

image.png

实现原理: 通过 keep-alive 组件插槽,获取第一个子节点。根据 include、exclude 判断是否需要缓存,通过组件的 key,判断是否命中缓存。利用 LRU 算法,更新缓存以及对应的 keys 数组。根据 max 控制缓存的最大组件数量

源码解析

源码位置:src/core/components/keep-alive.js

export default {
  name: 'keep-alive',
  abstract: true,

  props: {
    include: patternTypes,//名称匹配的组件包含
    exclude: patternTypes,//名称匹配的组件不包含
    max: [String, Number]//可缓存的数量
  },

  methods: {
    //缓存组件
    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)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
        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 () {
  // 实时监听include、exclude的变动
    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 () {
    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// 定义组件的缓存key
        // 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)// 调整key排序
      } else {
        // delay setting the cache until update
        this.vnodeToCache = vnode
        this.keyToCache = key
      }
      vnode.data.keepAlive = true
    }
    return vnode || (slot && slot[0])// 渲染和执行被包裹组件的钩子函数需要用到
  }//渲染函数  执行顺序 render->mounted
}

matches 函数

判断组件是否在include或exclude中

function matches (pattern: string | RegExp | Array<string>, name: string): boolean {
  if (Array.isArray(pattern)) {// include或exclude是数组的情况
    return pattern.indexOf(name) > -1
  } else if (typeof pattern === 'string') {// include或exclude是字符串的情况
    return pattern.split(',').indexOf(name) > -1
  } else if (isRegExp(pattern)) {// include或exclude是正则表达式的情况
    return pattern.test(name)
  }
  /* istanbul ignore next */
  return false// 都没匹配上
}

pruneCache 函数

如果缓存的组件不在include或exclude的规则内,则将组件从缓存中删除

function pruneCache (keepAliveInstance: any, filter: Function) {
  const { cache, keys, _vnode } = keepAliveInstance // keep-alive组件实例
  for (const key in cache) {
    const entry: ?CacheEntry = cache[key] // 已经被缓存的组件
    if (entry) {
      const name: ?string = entry.name
      // 若name存在且不能跟include或exclude匹配上就销毁这个已经缓存的组件
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

pruneCacheEntry 函数

删除缓存中的组件

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()// 执行组件的destory钩子函数
  }
  cache[key] = null
  remove(keys, key)// 删除对应的元素
}

LRU算法

LRU( least recently used)根据数据的历史记录来淘汰数据,重点在于保护最近被访问使用过的数据,淘汰现阶段最久未被访问的数据
LRU的主体思想在于:如果数据最近被访问过,那么将来被访问的几率也更高

image.png