vue的keep-Alive源码的解读

83 阅读5分钟

什么是keep-alive

keep-alive是Vue的内置组件,当它包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。

keep-alive是一个抽象组件,它自身不会渲染一个DOM元素,也不会出现在父组件中。

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

keep-alive的作用

在组件切换过程中 把切换出去的组件保留在内存中,防止重复渲染DOM,减少加载时间及性能消耗,提高用户体验性

keep-alive的原理

keep-alive 的属性

include - 字符串或正则表达式。只有名称匹配的组件会被缓存。

exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。

max - 最多可以缓存多少组件。

 props: {
     // 缓存白名单
    // 字符串或正则表达式。只有名称匹配的组件会被缓存
    include: patternTypes,
    // 缓存黑名单
    // 字符串或正则表达式。任何名称匹配的组件都不会被缓存。
    exclude: patternTypes,
    // 数字。最多可以缓存多少组件实例。
    max: [String, Number]
  },

include 和 exclude 属性允许组件有条件地缓存。二者都可以用逗号分隔字符串、正则表达式或一个数组来表示

渲染时

1.获取到插槽里面的内容

2.调用getFirstComponentChild方法获取第一个子组件,获取到该组件的name,如果有name属性就用name,没有就用tag名。

3.用获取到的name和传入的include,exclude属性进行匹配,如果匹配不成功,则表示不缓存该组件,直接返回这个组件的 vnode,否则的话走下一步缓存:

4.缓存机制:用拿到的name去this.cache对象中去寻找是否有该值,如果有则表示该组件有缓存,即命中缓存:

render () {
    const slot = this.$slots.default
    const vnode: VNode = getFirstComponentChild(slot)
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      // 获取组件名称,通过matchs方法来判断当前组件是否应该被缓存,如果没有组件在include中或者有组件在exclude中,就直接返回,不做任何操作
      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
     //产生一个key,如果vnode中有key值就用这个key,没有生成一个唯一的key
      const key: ?string = vnode.key == null
        ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
        : vnode.key
        //如果cache对象中有保存这个vnode实例,那么不用产生新的实例,使用缓存中原本的componentInstance身上的实例,并且将当前key值放在数组的最后一位,这样可以让它被删除的优先级降低
     //缓存的处理:
      if (cache[key]) {
        vnode.componentInstance = cache[key].componentInstance
        //调整该组件可以的顺序,将其重原来的地方删除并重新放在最后一个
        remove(keys, key)
        keys.push(key)
        //如果没有这个缓存,那么将vnode赋值给vnodeToCache,key赋值给ketToCache
      } else {
        // delay setting the cache until update
        this.vnodeToCache = vnode
        this.keyToCache = key
      }

      vnode.data.keepAlive = true
    }
    return vnode || (slot && slot[0])
  }

初始化

created 阶段会初始化两个变量,分别是 cache 和keys。

    created () {
    // 用于缓存 vnode 的对象
    this.cache = Object.create(null)
    //  已缓存的 vnode 的 key 集合
    this.keys = []
  },

destroyed钩子函数

该组件被销毁的时候清除cache缓存中的所有组件实例

destroyed () {
    // 清空所有缓存的 vnode
    // 使用 for in 遍历 this.cache 对象
    for (const key in this.cache) {
      // 借助 pruneCacheEntry 方法移除缓存的 vnode
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },

mounted 和 updated 方法

createVNode的执行时机在mounted和updated的,就是说只有挂载时或者更新时才会有机会更新缓存的vnode

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

methods

cacheVNode
这个函数的功能就是判断vnodeToCache是否存在,存在就将对应的vnode保存到cache中,key保存到keys中

  methods: {
    // 判断vnodeToCache是否存在,存在就将对应的vnode保存到cache中,key保存到keys中
    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
      }
    }
  },

pruneCacheEntry

该方法用于移除 cache 中缓存的指定 vnode,并销毁 vnode 对应的组件实例

function pruneCacheEntry (
   // 用于缓存 vnode 的对象
  cache: CacheEntryMap,
  // 当前要移除 vnode 的 key
  key: string,
// 已缓存vnode 的key集合
  keys: Array<string>,
  // keep-alive 内当前渲染组件的 vnode
  current?: VNode
) {
  //  使用 key 从 cache 中获取缓存的指定 vnode
  const entry: ?CacheEntry = cache[key]
  if (entry && (!current || entry.tag !== current.tag)) {
    // 触发执行 vnode 对应组件实例的 $destroy 方法
    entry.componentInstance.$destroy()
  }
  // 将 cache 对象中的 key 置为 null,删除缓存的 vnode
  cache[key] = null
 // 从 key 集合数组中移除 key 
  remove(keys, key)
}

pruneCache

用移除cache 中不满足filter 条件的vnode

// 用移除cache 中不满足filter 条件的vnode
function pruneCache (keepAliveInstance: any, filter: Function) {
  const { cache, keys, _vnode } = keepAliveInstance
  // 遍历cache 对象中已经缓存的vnode
  for (const key in cache) {
    // 获取当前遍历的vnode
    const entry: ?CacheEntry = cache[key]
    // 如果当前遍历的 vnode 不是 null 的话
    if (entry) {
       // 获取当前遍历 vnode 对应的组件名称
      const name: ?string = entry.name
      //  如果组件名称不满足 filter 条件的话,则调用 pruneCacheEntry 方法将当前遍历的 vnode 移除
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

执行顺序

第一步:获取keep-alive包裹着的第一个子组件对象及其组件名;

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

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

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

第五步:最后并且很重要,将该组件实例的keepAlive属性值设置为true。

最后就是再次渲染执行缓存和对应钩子函数了

如何销毁 组件的方式

keep-alive包裹的组件有两个声明函数 activated(组件激活的状态触发) 和 deactivated(组件非激活的状态处罚),想要销毁组件可以在 deactivated 中调用 $destroy() 方法来销毁当前组件。

利用 keep-alive 组件的 include 属性,将需要缓存的组件名通过keep-alive组件传值来控制是否缓存。

keep-alive 默认不支持销毁已缓存的组件,但是可以直接操控 cache(缓存组件列表) 数组直接移除已缓存的组件。

LRU缓存策略

我们知道keepAlive是有条件的缓存,既然有限制条件,那么旧的组件需要删除缓存,新的组件就需要加入到最新缓存。keepAlive采用了这样一种策略,LRU(Least recently used,最近最少被使用)策略根据数据的历史访问记录来进行淘汰数据,LRU 策略的设计原则是,如果一个数据在最近一段时间没有被访问到,那么在将来它被访问的可能性也很小。也就是说,当限定的空间已存满数据时,应当把最久没有被访问到的数据淘汰。keepAlive 缓存机制便是根据LRU策略来设置缓存组件新鲜度,当缓存达到上限时将很久未访问的组件从缓存中删除。

总结

eep-alive 组件实现功能的重点在其 render 函数中,render 函数会返回已经处理好的缓存的子组件 vnode,以此实现 keep-alive 组件的功能。

这里的处理是指返回 vnode 的 componentInstance 属性指向缓存 vnode 的 componentInstance 属性。通过上文可知,缓存 vnode 的 componentInstance 属性和componentInstance 属性中的 el属性是keepalive实现组件缓存功能的重点,通过这种处理,返回的vnode中就保存着这两个重要的数据。在接下来的处理逻辑中,只要将el属性是keep-alive 实现组件缓存功能的重点,通过这种处理,返回的 vnode 中就保存着这两个重要的数据。在接下来的处理逻辑中,只要将 el(真实 DOM) 重新渲染到页面上,就可以实现子组件 DOM 的复原了,由于之前的 Vue 实例已经赋值给 vnode.componentInstance,所以子组件的 Vue 实例也已经复原。至此,keep-alive 组件的功能也就实现了。