聊聊vue中的keep-alive

1177次阅读  |  发布于2年以前

一、什么是keep-alive?

官方介绍就是:<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 <transition> 相似,<keep-alive> 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在组件的父组件链中。

当组件在 <keep-alive> 内被切换时,它的 mountedunmounted 生命周期钩子不会被调用,取而代之的是 activateddeactivated

简单理解就是说我们可以把一些不常变动的组件或者需要缓存的组件用<keep-alive>包裹起来,这样<keep-alive>就会帮我们把组件保存在内存中,而不是直接的销毁,这样做可以保留组件的状态或避免多次重新渲染,以提高页面性能

二、使用用法

我们先根据官方文档来回顾一下<keep-alive>组件的具体用法,如下:

<keep-alive>组件可接收三个属性:

  <!-- 逗号分隔字符串 -->
  <keep-alive include="a,b">
    <component :is="view"></component>
  </keep-alive>

  <!-- regex (使用 `v-bind`) -->
  <keep-alive :include="/a|b/">
    <component :is="view"></component>
  </keep-alive>

  <!-- Array (使用 `v-bind`) -->
  <keep-alive :include="['a', 'b']">
    <component :is="view"></component>
  </keep-alive>

匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值)。匿名组件不能被匹配。

max表示最多可以缓存多少组件实例。一旦这个数字达到了,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉。


  <keep-alive :max="10">
    <component :is="view"></component>
  </keep-alive>

在这里简单介绍一个日常项目中有可能出现的场景并使用keep-alive来实现按需控制缓存 场景:当我们从首页–>列表页–>商品详情页–>返回到列表页(需要缓存)–>返回到首页(需要缓存)–>再次进入列表页(不需要缓存)

1 . 在路由meta对象里定义两个值:

keepAlive:这个路由是否需要缓存

deepth:代表页面之间的前进后退的层级关系

   {
       path: '*',
       name: 'Home',
       component: () => import(/* webpackPreload: true */ '@/views/home'),
       meta: {
         keepAlive: true,
         deepth: 1
       }
     },
     {
       path: '/list',
       name: 'list',
       component: () => import('@/views/list'),
       meta: {
         keepAlive: true,
         deepth: 2
       }
     },
     {
       path: '/detail',
       name: 'Detail',
       component: () => import('@/views/detail'),
       meta: {
         keepAlive: true,
         deepth: 3
       }
     },

2 . 监听路由动态控制需要缓存的值

   //3x版本router-view不允许直接写在keep-alive里面,需注意
   <template>
     <div id="app">
       <keep-alive :include="include">
         <router-view v-if="$route.meta.keepAlive" />
       </keep-alive>
       <router-view v-if="!$route.meta.keepAlive" />
     </div>
   </template>

   export default {
     data() {
       return {
         include: []
       };
     },
     watch: {
       $route(to, from) {
         // 如果要to(进入)的页面是需要keepAlive缓存的,把name push进include数组中
         if (to.meta.keepAlive) {
           !this.include.includes(to.name) && this.include.push(to.name);
         }
         // 如果 要 form(离开) 的页面是 keepAlive缓存的,
         // 再根据 deepth 来判断是前进还是后退
         // 如果是后退:
         if (from.meta.keepAlive && to.meta.deepth < from.meta.deepth) {
           const index = this.include.indexOf(from.name);
           index !== -1 && this.include.splice(index, 1);
         }
       }
     }
   };

以上场景在通过监听路由,动态的设置了在第一次进入并回退回来时的缓存实现,并在第二次进入时重新开始进行新一轮缓存设置,实现动态控制缓存。

三、实现

<keep-alive>组件的定义位于源码的 src/core/components/keep-alive.js 文件中,本文参考:https://unpkg.com/browse/vue@2.6.12/src/core/components/keep-alive.js,感兴趣的可以自行查看,下面只展示部分代码。

const patternTypes: Array<Function> = [String, RegExp, Array]

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 () {
    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
      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钩子开始进行分析:

created:

created 钩子函数里定义并初始化了两个属性: this.cachethis.keys

created () {
    this.cache = Object.create(null)
    this.keys = []
}

this.cache是一个对象,用来存储需要缓存的组件。

this.keys是一个数组,用来存储每个需要缓存的组件的key,即对应this.cache对象中的键值。

destroyed:

<keep-alive>组件被销毁时,此时会调用destroyed钩子函数,在该钩子函数里会遍历this.cache对象,然后将那些被缓存的并且当前没有处于被渲染状态的组件都销毁掉并将其从this.cache对象中删除。如下:

destroyed () {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
}

上面用到了pruneCacheEntry函数:

function pruneCacheEntry (
  cache: VNodeCache,
  key: string,
  keys: Array<string>,
  current?: VNode
) {
  const cached = cache[key]
  /* 判断当前没有处于被渲染状态的组件,将其销毁*/
  if (cached && (!current || cached.tag !== current.tag)) {
    cached.componentInstance.$destroy()
  }
  cache[key] = null
  remove(keys, key)
}
mounted:

mounted钩子函数中观测 includeexclude 的变化,如下:

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

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

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

在该函数内对this.cache对象进行遍历,取出每一项的name值,用其与新的缓存规则进行匹配,如果匹配不上,则表示在新的缓存规则下该组件已经不需要被缓存,则调用pruneCacheEntry函数将这个已经不需要缓存的组件实例先销毁掉,然后再将其从this.cache对象中删除。

render:

<keep-alive> 为一个函数式组件。执行组件渲染的时候,就会执行到这个 render 函数

render () {
   /* 获取默认插槽中的第一个组件节点 */
    const slot = this.$slots.default
    const vnode: VNode = getFirstComponentChild(slot)
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      /* 获取该组件节点的名称 */
      const name: ?string = getComponentName(componentOptions) 
      /* 如果name与include规则不匹配或者与exclude规则匹配则表示不缓存,直接返回vnode */
      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 */
      const key: ?string = vnode.key == null
        ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
        : vnode.key
      /* 如果命中缓存,则直接从缓存中拿 vnode 的组件实例 */
      if (cache[key]) {
        vnode.componentInstance = cache[key].componentInstance
        // make current key freshest 调整该组件key的顺序,将其从原来的地方删掉并重新放在最后一个 
        remove(keys, key)
        keys.push(key)
      } else {
        /* 如果没有命中缓存,则将其设置进缓存 */
        cache[key] = vnode
        keys.push(key)
        // prune oldest entry 如果配置了max并且缓存的长度超过了this.max,则从缓存中删除第一个
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
      }

      vnode.data.keepAlive = true
    }
    return vnode || (slot && slot[0])
  }
  1. 获取默认插槽中的第一个组件节点。 由于我们也是在 <keep-alive> 标签内部写 DOM,所以可以先获取到它的默认插槽,然后再获取到它的第一个子节点。<keep-alive> 只处理第一个子元素,所以一般和它搭配使用的有 component 动态组件或者是 router-view
  2. 获取该组件节点的名称,然后用组件名称跟 includeexclude 中的匹配规则去匹配,如果组件名称与 include 规则不匹配或者与 exclude 规则匹配,则表示不缓存该组件,直接返回这个组件的 vnode,否则的话走下一步缓存
  3. 获取组件的key值:拿到key值后去this.cache对象中去寻找是否有该值,如果有则表示该组件有缓存,即命中缓存,直接从缓存中拿 vnode 的组件实例,此时重新调整该组件key的顺序,将其从原来的地方删掉并重新放在this.keys中最后一个。没有继续下一步
  4. 表明该组件还没有被缓存过,则以该组件的key为键,组件vnode为值,将其存入this.cache中,并且把key存入this.keys中。此时再判断this.keys中缓存组件的数量是否超过了设置的最大缓存数量值this.max,如果超过了,则把第一个缓存组件删掉
  5. 最后设置 vnode.data.keepAlive = true ,最后将vnode返回

总结

上面介绍了Vue中的内置组件<keep-alive>组件以及<keep-alive>组件的具体用法。同时也分析了<keep-alive>组件的一些内部原理,底下则是个人对于keep-alive的运行的一些个人理解总结: keep-alive主要作用是缓存vnode,大概可以分为三个运行阶段

  1. 初始未存在缓存阶段,在created钩子定义了用于保存vnode的cache对象以及保存缓存了的vnode列表keys,用于数据的存储。mounted钩子观测监听 includeexclude 的变化,进行缓存vnode的变化更新,最后调用render进行组件vnode的第一次缓存设置。 因为缓存一些具体业务功能的组件vnode对于我们来说,什么时候开始缓存、何时销毁以及何时运行render重新刷新,开发者是没有vnode的直接控制能力,所以需要定义一些属性include、exclude、max来进行一个判断,用于更准确的对需要缓存的vnode进行控制处理。
  2. 已缓存的更新阶段,调用render函数直接从cache对象返回已缓存的vnode,避免了多次的重新渲染,来提高页面性能。
  3. 销毁阶段,destroyed钩子定义组件销毁时清除那些被缓存的并且当前没有处于被渲染状态的组件。销毁组件时,对于缓存的vnode对象,不清除的话应该也会造成一些内存上的占用或者内存泄漏的问题,所以在销毁时需要进行一个清除缓存的操作。

以上就是关于keep-alive的相关内容,希望每个看完的同学都有自己收获,完结

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8