从源码学习Vue.js系列 -- keep-alive

961 阅读1分钟

一、什么是 keep-alive

keep-alive 是 Vue 的一个内置组件,它可以讲组件实例保存在内存中,组件的切换并不会将保存的组件实例进行销毁。

二、API

keep-alive 提供了 includeexclude 两个属性,允许组件有条件地进行缓存。这两个属性中的值可以是以逗号分割的字符串、数组或者正则表达式。

<keep-alive include="a,b">
  <component></component>
</keep-alive>
<keep-alive :include="['a','b']">
  <component></component>
</keep-alive>

三、如何与钩子函数结合

keep-alive 缓存的组件被激活以后,会触发 activated 钩子;缓存的组件被停用以后会触发 deactivated 钩子。

四、源码中的描述

在 Vue.js 的源码中,有一个 keep-alive.js 模块,就是具体的功能实现。


/* keep-alive组件 */
export default {
  name: 'keep-alive',
  /* 抽象组件 */
  abstract: true,

  props: {
    include: patternTypes,
    exclude: patternTypes
  },

  created () {
    /* 缓存对象 */
    this.cache = Object.create(null)
  },

  /* destroyed钩子中销毁所有cache中的组件实例 */
  destroyed () {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache[key])
    }
  },

  watch: {
    /* 监视include以及exclude,在被修改的时候对cache进行修正 */
    include (val: string | RegExp) {
      pruneCache(this.cache, this._vnode, name => matches(val, name))
    },
    exclude (val: string | RegExp) {
      pruneCache(this.cache, this._vnode, name => !matches(val, name))
    }
  },

  render () {
    const vnode: VNode = getFirstComponentChild(this.$slots.default)
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      const name: ?string = getComponentName(componentOptions)
      /* name不在inlcude中或者在exlude中则直接返回vnode(没有取缓存) */
      if (name && (
        (this.include && !matches(this.include, name)) ||
        (this.exclude && matches(this.exclude, name))
      )) {
        return vnode
      }
      const key: ?string = vnode.key == null
        ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
        : vnode.key
      /* 直接从缓存中获取组件实例给vnode,未缓存则进行缓存 */
      if (this.cache[key]) {
        vnode.componentInstance = this.cache[key].componentInstance
      } else {
        this.cache[key] = vnode
      }
      vnode.data.keepAlive = true
    }
    return vnode
  }
}