Vue源码解析之keep-alive

58 阅读8分钟

什么是keep-alive?

<keep-alive>Vue中内置的一个抽象组件,它自身不会渲染一个 DOM 元素,也不会出现在父组件链中。当它包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。

和 相似, 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在组件的父组件链中。

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

用法

我们想要缓存某个组件,只要用组件将其包裹就行。常用的用法是包裹组件缓存动态组件,或者包裹缓存路由页面。

比如常在router.js路由表里定义好哪些页面需要缓存,就可以通过下面这样实现了:
      path: "/index",
      name: 'index',   
      component: () => import(/* webpackChunkName: "index" */ '@/pages/index'),
      meta: {
        title: '首页', 
        keepAlive: true
      },
    },
<keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive && isRouterAlive"></router-view>
<keep-alive>组件可以接收三个属性:
  • include - 字符串或正则表达式。只有名称匹配的组件会被缓存。

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

  • max - 数字。最多可以缓存多少组件实例。

    `include` 和 `exclude` 属性允许组件有条件地缓存。二者都可以用逗号分隔字符串、正则表达式或一个数组来表示:
    
<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>
 
<!-- 正则表达式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>
 
<!-- 数组 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>

注意:

  • 想要缓存的组件一定要给定name属性,并且要和** **include,exclude给定的值一致
  • 只渲染其直系的一个组件,因此若在 中用 v-for,则其不会工作,若多条件判断有多个符合条件也同理不工作。
  • include 和 exclude 匹配时,首先检查组件的 name 选项,若 name 选项不可用,则匹配它的局部注册名称 (即父组件 components 选项的键值)。匿名组件不能被匹配。
  • 不会在函数式组件中正常工作,因为它们没有缓存实例。

源码解析

// isRegExp函数判断是不是正则表达式,remove移除数组中的某一个成员
// getFirstComponentChild获取VNode数组的第一个有效组件
import { isRegExp, remove } from 'shared/util'
import { getFirstComponentChild } from 'core/vdom/helpers/index'
​
type VNodeCache = { [key: string]: ?VNode }; // 缓存组件VNode的缓存类型// 通过组件的name或组件tag来获取组件名(上面注意的第二点)
function getComponentName (opts: ?VNodeComponentOptions): ?string {
 return opts && (opts.Ctor.options.name || opts.tag)
}
​
// 判断include或exclude跟组件的name是否匹配成功
function matches (pattern: string | RegExp | Array<string>, name: string): boolean {
 if (Array.isArray(pattern)) {
 return pattern.indexOf(name) > -1 // include或exclude是数组的情况
 } else if (typeof pattern === 'string') {
 return pattern.split(',').indexOf(name) > -1 // include或exclude是字符串的情况
 } else if (isRegExp(pattern)) {
 return pattern.test(name) // include或exclude是正则表达式的情况
 }
 return false // 都没匹配上(上面注意的二三点)
}
​
// 销毁缓存
function pruneCache (keepAliveInstance: any, filter: Function) {
 const { cache, keys, _vnode } = keepAliveInstance // keep-alive组件实例
 for (const key in cache) {
 const cachedNode: ?VNode = cache[key] // 已经被缓存的组件
 if (cachedNode) {
  const name: ?string = getComponentName(cachedNode.componentOptions)
  // 若name存在且不能跟include或exclude匹配上就销毁这个已经缓存的组件
  if (name && !filter(name)) {
  pruneCacheEntry(cache, key, keys, _vnode)
  }
 }
 }
}
​
// 销毁缓存的入口
function pruneCacheEntry (
 cache: VNodeCache,
 key: string,
 keys: Array<string>,
 current?: VNode
) {
 const cached = cache[key] // 被缓存过的组件
 // “已经被缓存的组件是否继续被缓存” 有变动时
 // 若组件被缓存命中过且当前组件不存在或缓存命中组件的tag和当前组件的tag不相等
 if (cached && (!current || cached.tag !== current.tag)) {
 // 说明现在这个组件不需要被继续缓存,销毁这个组件实例
 cached.componentInstance.$destroy()
 }
 cache[key] = null // 把缓存中这个组件置为null
 remove(keys, key) // 把这个组件的key移除出keys数组
}
​
// 示例类型
const patternTypes: Array<Function> = [String, RegExp, Array]
​
// 向外暴露keep-alive组件的一些选项
export default {
 name: 'keep-alive', // 组件名
 abstract: true, // keep-alive是抽象组件// 用keep-alive组件时传入的三个props
 props: {
 include: patternTypes,
 exclude: patternTypes,
 max: [String, Number]
 },
​
 created () {
 this.cache = Object.create(null) // 存储需要缓存的组件
 this.keys = [] // 存储每个需要缓存的组件的key,即对应this.cache对象中的键值
 },
​
 // 销毁keep-alive组件的时候,对缓存中的每个组件执行销毁
 destroyed () {
 for (const key in this.cache) {
  pruneCacheEntry(this.cache, key, this.keys)
 }
 },
​
 // keep-alive组件挂载时监听include和exclude的变化,条件满足时就销毁已缓存的组件
 mounted () {
 this.$watch('include', val => {
  pruneCache(this, name => matches(val, name))
 })
 this.$watch('exclude', val => {
  pruneCache(this, name => !matches(val, name))
 })
 },
​
 // 重点来了
 render () {
 const slot = this.$slots.default // keep-alive组件的默认插槽
 const vnode: VNode = getFirstComponentChild(slot) // 获取默认插槽的第一个有效组件
 // 如果vnode存在就取vnode的选项
 const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
 if (componentOptions) {
  //获取第一个有效组件的name
  const name: ?string = getComponentName(componentOptions)
  const { include, exclude } = this // props传递来的include和exclude
  if (
  // 若include存在且name不存在或name未匹配上
  (include && (!name || !matches(include, name))) ||
  // 若exclude存在且name存在或name匹配上
  (exclude && name && matches(exclude, name))
  ) {
  return vnode // 说明不用缓存,直接返回这个组件进行渲染
  }
  
  // 匹配上就需要进行缓存操作
  const { cache, keys } = this // keep-alive组件的缓存组件和缓存组件对应的key
  // 获取第一个有效组件的key
  const key: ?string = vnode.key == null
  // 同一个构造函数可以注册为不同的本地组件
  // 所以仅靠cid是不够的,进行拼接一下
  ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
  : vnode.key
  // 如果这个组件命中缓存
  if (cache[key]) {
  // 这个组件的实例用缓存中的组件实例替换
  vnode.componentInstance = cache[key].componentInstance
  // 更新当前key在keys中的位置
  remove(keys, key) // 把当前key从keys中移除
  keys.push(key) // 再放到keys的末尾
  } else {
  // 如果没有命中缓存,就把这个组件加入缓存中
  cache[key] = vnode
  keys.push(key) // 把这个组件的key放到keys的末尾
  // 如果缓存中的组件个数超过传入的max,销毁缓存中的LRU组件
  if (this.max && keys.length > parseInt(this.max)) {
   pruneCacheEntry(cache, keys[0], keys, this._vnode)
  }
  }
​
  vnode.data.keepAlive = true // 设置这个组件的keepAlive属性为true
 }
 // 若第一个有效的组件存在,但其componentOptions不存在,就返回这个组件进行渲染
 // 或若也不存在有效的第一个组件,但keep-alive组件的默认插槽存在,就返回默认插槽的第一个组件进行渲染
 return vnode || (slot && slot[0])
 }
}

原理

  name: 'keep-alive',
  abstract: true,
 
  props: {
    include: [String, RegExp, Array],
    exclude: [String, RegExp, Array],
    max: [String, Number]
  },
 
  created () {
    this.cache = Object.create(null)
    this.keys = []
  },
 
  destroyed () {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },
 
  mounted () {
    this.$watch('include', val => {
      pruneCache(this, name => matches(val, name))
    })
    this.$watch('exclude', val => {
      pruneCache(this, name => !matches(val, name))
    })
  },
 
  render() {
    /* 获取默认插槽中的第一个组件节点 */
    const slot = this.$slots.default
    const vnode = getFirstComponentChild(slot)
    /* 获取该组件节点的componentOptions */
    const componentOptions = vnode && vnode.componentOptions
 
    if (componentOptions) {
      /* 获取该组件节点的名称,优先获取组件的name字段,如果name不存在则获取组件的tag */
      const name = getComponentName(componentOptions)
 
      const { include, exclude } = this
      /* 如果name不在inlcude中或者存在于exlude中则表示不缓存,直接返回vnode */
      if (
        (include && (!name || !matches(include, name))) ||
        // excluded
        (exclude && name && matches(exclude, name))
      ) {
        return vnode
      }
 
      const { cache, keys } = this
      const key = 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 {
        cache[key] = vnode
        keys.push(key)
        // prune oldest entry
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
      }
 
      vnode.data.keepAlive = true
    }
    return vnode || (slot && slot[0])
  }
}

上文中用到了有created,destroyed,mounted,render四个钩子,下面我们来介绍一下四个钩子在上文中的作用,最后再总结一下整体流程。

created与destroyed钩子

created钩子会创建一个cache对象,用来作为缓存容器,保存vnode节点。

destroyed钩子则在组件被销毁的时候清除cache缓存中的所有组件实例。

    this.cache = Object.create(null)
    this.keys = []
  },
 
  destroyed () {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },

render钩子

重点来了,keep-alive实现缓存的核心代码就在这个钩子函数里。

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

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

/* 获取该组件节点的名称 */
const name = getComponentName(componentOptions)
 
/* 优先获取组件的name字段,如果name不存在则获取组件的tag */
function getComponentName (opts: ?VNodeComponentOptions): ?string {
  return opts && (opts.Ctor.options.name || opts.tag)
}
  1. 用获取到的name和传入的include,exclude属性进行匹配,如果匹配不成功,则表示不缓存该组件,直接返回这个组件的 vnode,否则的话走下一步缓存:

匹配:

/* 如果name与include规则不匹配或者与exclude规则匹配则表示不缓存,直接返回vnode */
if (
    (include && (!name || !matches(include, name))) ||
    // excluded
    (exclude && name && matches(exclude, name))
) {
    return vnode
}
  1. 缓存机制:用拿到的name去this.cache对象中去寻找是否有该值,如果有则表示该组件有缓存,即命中缓存:

缓存的处理:

if (cache[key]) {
    vnode.componentInstance = cache[key].componentInstance
    /* 调整该组件key的顺序,将其从原来的地方删掉并重新放在最后一个 */
    remove(keys, key)
    keys.push(key)
} 
/* 如果没有命中缓存,则将其设置进缓存 */
else {
    cache[key] = vnode
    keys.push(key)
    /* 如果配置了max并且缓存的长度超过了this.max,则从缓存中删除第一个 */
    if (this.max && keys.length > parseInt(this.max)) {
        pruneCacheEntry(cache, keys[0], keys, this._vnode)
    }
}
/* 最后设置keepAlive标记位 */
vnode.data.keepAlive = true

命中缓存时会直接从缓存中拿 vnode 的组件实例,此时重新调整该组件key的顺序,将其从原来的地方删掉并重新放在this.keys中最后一个。

如果没有命中缓存,即该组件还没被缓存过,则以该组件的key为键,组件vnode为值,将其存入this.cache中,并且把key存入this.keys中。此时再判断this.keys中缓存组件的数量是否超过了设置的最大缓存数量值this.max,如果超过了,则把第一个缓存组件删掉。

那么问题来了:为什么要删除第一个缓存组件并且为什么命中缓存了还要调整组件key的顺序?

这其实应用了一个缓存淘汰策略LRU: LRU算法是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰。该算法赋予每个页面一个访问字段,用来记录一个页面自上次被访问以来所经历的时间 t,当须淘汰一个页面时,选择现有页面中其 t 值最大的,即最近最少使用的页面予以淘汰。

截屏2022-09-22 15.10.15.png

  1. 将新数据从尾部插入到this.keys中;
  2. 每当缓存命中(即缓存数据被访问),则将数据移到this.keys的尾部;
  3. this.keys满的时候,将头部的数据丢弃;

mounted钩子

在这个钩子函数里,调用了pruneCache方法,以观测 include 和 exclude 的变化。

如果include 或exclude 发生了变化,即表示定义需要缓存的组件的规则或者不需要缓存的组件的规则发生了变化,那么就执行pruneCache函数,函数如下::

function pruneCache (keepAliveInstance, filter) {
  const { cache, keys, _vnode } = keepAliveInstance
  for (const key in cache) {
    const cachedNode = cache[key]
    if (cachedNode) {
      const name = getComponentName(cachedNode.componentOptions)
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

在该函数内对this.cache对象进行遍历,取出每一项的name值,用其与新的缓存规则进行匹配,如果匹配不上,则表示在新的缓存规则下该组件已经不需要被缓存,则调用pruneCacheEntry函数将其从this.cache对象剔除即可。

缓存后如何获取数据

解决方案可以有以下两种:

  • beforeRouteEnter

    每次组件渲染的时候,都会执行beforeRouteEnter

截屏2022-09-22 15.27.50.png

  • actived

在keep-alive缓存的组件被激活的时候,都会执行actived钩子

截屏2022-09-22 15.28.28.png 注意:服务器端渲染期间avtived不被调用

总结

另外,组件一旦被 缓存,那么再次渲染的时候就不会执行 created、mounted 等钩子函数。使用keepalive组件后,被缓存的组件生命周期会多activated和deactivated 两个钩子函数,它们的执行时机分别是 包裹的组件激活时调用和停用时调用。