简析keep-alive

149 阅读1分钟

作用:

在组件切换过程中保存组件的状态,避免重复渲染DOM

两个钩子函数:

1.将组件状态缓存到内存中,触发deactivated钩子函数

2.当组件被重新激活时,触发activated钩子函数

注意: 只有组件被keep-alive包裹时,这两个生命周期函数才会被调用,如果作为正常组件使用,是不会生效的。常搭配include、exclude使用。

举例说明:

比如A页面现在滚动的位置是1/2,然后切换到B页面,再切换回来的时候页面的滚动位置还会保留。在这个过程中就需要使用到keep-alive对组件进行缓存与激活处理。

源码解析:

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

  props: {
    include: patternTypes,
    exclude: patternTypes,
    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 () {
    // 会监控 include 和 exclude 属性,进行组件的缓存处理
    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: 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
        // 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
      // 如果组件没有 key, 表示就没有缓存,有 key 表示就缓存过了,直接获取组件的实例
      if (cache[key]) {
        vnode.componentInstance = cache[key].componentInstance
        // make current key freshest
        remove(keys, key) // 删除当前的key
        keys.push(key) // 并把key放到最后面
      } else {
        cache[key] = vnode // 缓存vnode
        keys.push(key) // 将key放到最后面
        // prune oldest entry
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)  // 超过了最大限制就删除第0个
        }
      }

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