Keep-alive

144 阅读2分钟

keep-alive是什么

API — Vue.js (vuejs.org)

概念

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

作用

keep-alive作为一种vue的内置组件,主要作用是缓存组件状态。当需要组件的切换时,不用重新渲染组件,避免多次渲染,就可以使用keep-alive包裹组件

keep-alive 用法

可传参数

  • include 字符串或者正则表达式,只有名称匹配的组件会被缓存
  • exclude 字符串或者正则表达式,任何名臣匹配的组件都不会被缓存
  • max 数字,最多可以缓存多少组件实例

使用

在动态组件中的应用

<keep-alive :include="whiteList" :exclude="blackList" :max="amount">
  <component :is="currentComponent"></component>
</keep-alive>

include定义缓存白名单,keep-alive会缓存命中的组件;exclude定义缓存黑名单,被命中的组件将不会被缓存;max定义缓存组件上限,超出上限使用LRU的策略置换缓存数据。

生命周期函数

  1. activated

      在 keep-alive 组件激活时调用       该钩子函数在服务器端渲染期间不被调用

  2. deactivated

      在 keep-alive 组件停用时调用       该钩子在服务器端渲染期间不被调用

    被包含在 keep-alive 中创建的组件,会多出两个生命周期的钩子: activateddeactivated

    使用 keep-alive 会将数据保留在内存中,如果要在每次进入页面的时候获取最新的数据,需要在 activated 阶段获取数据,承担原来 created 钩子函数中获取数据的任务。

源码剖析

vue/keep-alive.js at 2.6 · vuejs/vue · GitHub


export default {
  name: 'keep-alive',
  abstract: true,
 
  props: {
    include: patternTypes,
    exclude: patternTypes,
    max: [String, Number]
  },
 
  created () {
    this.cache = Object.create(null) // 创建缓存虚拟dom的列表
    this.keys = [] // 创建缓存组件的key列表
  },
 
  destroyed () {
    for (const key in this.cache) {// keep-alive销毁时,循环清空所有的缓存和key
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },
 
  mounted () {// 会监控include 和 include属性 进行组件的缓存处理
    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和cid 拼接一个key
      if (cache[key]) { // 如果缓存中有key
        vnode.componentInstance = cache[key].componentInstance // 直接拿到组件实例
        // make current key freshest
        remove(keys, key) // 删除当前的key // LRU 最近最久未使用法
        keys.push(key)  // 并将key放到缓存的最后面
      } else {
        cache[key] = vnode // 缓存vnode
        keys.push(key) // 将key 存入
        // prune oldest entry
        if (this.max && keys.length > parseInt(this.max)) { // 缓存的太多超过了max就需要删除掉
 
          pruneCacheEntry(cache, keys[0], keys, this._vnode) // 要删除第0个 但是现在渲染的就是第0个
        }
      }
 
      vnode.data.keepAlive = true // 并且标准keep-alive下的组件是一个缓存组件
    }
    return vnode || (slot && slot[0]) // 返回当前的虚拟节点
  }