keep-alive

keep-alive是vue的一个内置组件

1. 官方介绍及其用法

  • Props
    • include - string | RegExp | Array。只有名称匹配的组件会被缓存。
    • exclude - string | RegExp | Array。任何名称匹配的组件都不会被缓存。
    • max - number | string。最多可以缓存多少组件实例
  • 用法

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

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

    主要用于保留组件状态或避免重新渲染。

    <!-- 基本 -->
    <keep-alive>
      <component :is="view"></component>
    </keep-alive>
    
    <!-- 多个条件判断的子组件 -->
    <keep-alive>
      <comp-a v-if="a > 1"></comp-a>
      <comp-b v-else></comp-b>
    </keep-alive>
    
    <!-- 和 `<transition>` 一起使用 -->
    <transition>
      <keep-alive>
        <component :is="view"></component>
      </keep-alive>
    </transition>
    

    注意 : <keep-alive> 是用在其一个直属的子组件被切换的情形。如果你在其中有 v-for 则不会工作。如果有上述的多个条件性的子元素, 要求同时只有一个子元素被渲染。

  • include 和 exclude

    The include 和 exclude prop 允许组件有条件地缓存。二者都可以用逗号分隔字符串、正则表达式或一个数组来表示:

    <!-- 逗号分隔字符串 -->
    <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> 不会在函数式组件中正常工作,因为它们没有缓存实例。

2. 源码分解

该组件的定义在 src/core/components/keep-alive.js 中

2.1 源码

export default {
  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])
  }
}

首先我们可以看到该组件内没有常规的等标签,因为它不是一个常规的模板组件,取而代之的是它内部多了一个叫做render的函数,它是一个函数式组件,执行 组件渲染的时候,就会执行到这个 render 函数。
2.2 props
在props选项内接收传进来的三个属性:include、exclude和max。如下:

props: {
    include: [String, RegExp, Array],
    exclude: [String, RegExp, Array],
    max: [String, Number]
}

include 表示只有匹配到的组件会被缓存,而 exclude 表示任何匹配到的组件都不会被缓存, max表示缓存组件的数量,因为我们是缓存的 vnode 对象,它也会持有 DOM,当我们缓存的组件很多的时候,会比较占用内存,所以该配置允许我们指定缓存组件的数量。
2.3 created
在 created 钩子函数里定义并初始化了两个属性: this.cache 和 this.keys。

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

this.cache是一个对象,用来存储需要缓存的组件,它将以如下形式存储:

this.cache = {
    'key1':'组件1',
    'key2':'组件2',
    // ...
}

this.keys是一个数组,用来存储每个需要缓存的组件的key,即对应this.cache对象中的键值。
2.4 destroyed
当组件被销毁时,此时会调用destroyed钩子函数,在该钩子函数里会遍历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)
}

2.5 mounted
在mounted钩子函数中观测 include 和 exclude 的变化,如下:

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

如果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对象剔除即可。
2.6 render
接下来就是重头戏render函数,也是本篇文章中的重中之重。以上工作都是一些辅助工作,真正实现缓存功能的就在这个render函数里。

在render函数中首先获取第一个子组件节点的 vnode:

/* 获取默认插槽中的第一个组件节点 */
const slot = this.$slots.default
const vnode = getFirstComponentChild(slot)

由于我们也是在 标签内部写 DOM,所以可以先获取到它的默认插槽,然后再获取到它的第一个子节点。 只处理第一个子元素,所以一般和它搭配使用的有 component 动态组件或者是 router-view。这也是官方介绍里面提到的要求同时只有一个子元素被渲染

接下来获取该组件节点的名称:

/* 获取该组件节点的名称 */
const name = getComponentName(componentOptions)

/* 优先获取组件的name字段,如果name不存在则获取组件的tag */
function getComponentName (opts: ?VNodeComponentOptions): ?string {
  return opts && (opts.Ctor.options.name || opts.tag)
}

然后用组件名称跟 include、exclude 中的匹配规则去匹配:

const { include, exclude } = this
/* 如果name与include规则不匹配或者与exclude规则匹配则表示不缓存,直接返回vnode */
if (
    (include && (!name || !matches(include, name))) ||
    // excluded
    (exclude && name && matches(exclude, name))
) {
    return vnode
}

如果组件名称与 include 规则不匹配或者与 exclude 规则匹配,则表示不缓存该组件,直接返回这个组件的 vnode,否则的话走下一步缓存:

const { cache, keys } = this
/* 获取组件的key */
const key = vnode.key == null
? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key

/* 如果命中缓存,则直接从缓存中拿 vnode 的组件实例 */
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

首先获取组件的key值:

const key = vnode.key == null? 
componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key

拿到key值后去this.cache对象中去寻找是否有该值,如果有则表示该组件有缓存,即命中缓存:

/* 如果命中缓存,则直接从缓存中拿 vnode 的组件实例 */
if (cache[key]) {
    vnode.componentInstance = cache[key].componentInstance
    /* 调整该组件key的顺序,将其从原来的地方删掉并重新放在最后一个 */
    remove(keys, key)
    keys.push(key)
} 

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

如果this.cache对象中没有该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)
    }
}

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

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

这其实应用了一个缓存淘汰策略LRU:

LRU(Least recently
used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”。

它的算法是这样子的:
在这里插入图片描述

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

LRU的核心思想是如果数据最近被访问过,那么将来被访问的几率也更高,所以我们将命中缓存的组件key重新插入到this.keys的尾部,这样一来,this.keys中越往头部的数据即将来被访问几率越低,所以当缓存数量达到最大值时,我们就删除将来被访问几率最低的数据,即this.keys中第一个缓存的组件。这也就是在这也是官方介绍里面提到的已缓存组件中最久没有被访问的实例会被销毁掉的原因所在。

以上工作做完后设置 vnode.data.keepAlive = true ,最后将vnode返回。

以上就是render函数的整个过程。

3. 生命周期钩子

我们先了解一下activated和deactivated

  • activated:被 keep-alive 缓存的组件激活时调用。该钩子在服务器端渲染期间不被调用。
  • deactivated:被 keep-alive 缓存的组件停用时调用。该钩子在服务器端渲染期间不被调

组件一旦被 缓存,那么再次渲染的时候就不会执行 created、mounted 等钩子函数,下面我们就通过一个简单的例子来演示一下这两个钩子函数,示例如下

let A = {
  template: '<div class="a">' +
  '<p>A Comp</p>' +
  '</div>',
  name: 'A',
  mounted(){
  	console.log('Comp A mounted')
  },
  activated(){
  	console.log('Comp A activated')  
  },
  deactivated(){
  	console.log('Comp A deactivated')  
  }
}

let B = {
  template: '<div class="b">' +
  '<p>B Comp</p>' +
  '</div>',
  name: 'B',
  mounted(){
  	console.log('Comp B mounted')
  },
  activated(){
  	console.log('Comp B activated')  
  },
  deactivated(){
  	console.log('Comp B deactivated')  
  }
}

let vm = new Vue({
  el: '#app',
  template: '<div>' +
  '<keep-alive>' +
  '<component :is="currentComp">' +
  '</component>' +
  '</keep-alive>' +
  '<button @click="change">switch</button>' +
  '</div>',
  data: {
    currentComp: 'A'
  },
  methods: {
    change() {
      this.currentComp = this.currentComp === 'A' ? 'B' : 'A'
    }
  },
  components: {
    A,
    B
  }
})

在上述代码中,我们定义了两个组件A和B并为其绑定了钩子函数,并且在根组件中用 <keep-alive>组件包裹了一个动态组件,这个动态组件默认指向组件A,当点击switch按钮时,动态切换组件A和B。我们来看下效果:当第一次打开页面时,组件A被挂载,执行了组件A的mounted和activated钩子函数,当点击switch按钮后,组件A停止调用,同时组件B被挂载,此时执行了组件A的deactivated和组件B的mounted和activated钩子函数。此时再点击switch按钮,组件B停止调用,组件A被再次激活,我们发现现在只执行了组件A的activated钩子函数,这就验证了文档中所说的组件一旦被 缓存,那么再次渲染的时候就不会执行 created、mounted 等钩子函数。

4.需求案例

初次进入此页面,默认展示左侧的树形结构菜单,点击某一菜单,右侧加载该菜单相应的数据列表,由列表进入详情内页,然后再返回该页面,希望该页面保留了用户之前选择的树形菜单及数据列表。若从其他页面进入此页面,则不需要缓存
在这里插入图片描述

案例实践

思路:结合 router 中设置 meta 信息,缓存列表页。

  1. 设置路由的 meta 信息 ,添加是否需要缓存的标识keepAlive
const List = () => import(/* webpackChunkName: "list" */ '../pages/List.vue')
const Detail = () => import(/* webpackChunkName: "detail" */ '../pages/Detail.vue')
{
    path: 'list',
    name: 'list',
    component: List,
    meta: {
        title: '列表',
        keepAlive: true, //需要缓存
        isKeep: false
    }
},
{
    path: 'dist',
    name: 'detail',
    component: Detail
}
  1. 修改渲染匹配视图组件 router-view(一般是 app.vue 文件,根据实际需求会不一样),
    方法一:在其中加入判断语句区别是否是需要缓存的组件
<div class="container">
    <keep-alive> 
        <!-- 需要缓存的视图组件 -->
        <router-view v-if="$route.meta.keepAlive"></router-view> 
     </keep-alive>
      <!-- 不需要缓存的视图组件 -->
     <router-view v-if="!$route.meta.keepAlive"></router-view>
</div>

方法二: 使用 keep-alive 组件的 include/exclude 属性,include 表示要缓存的组件名(定义时的 name 属性),而 exclude 相反,匹配到的组件不会被缓存

<div class="container">
    <keep-alive include="list">
        <router-view></router-view> 
     </keep-alive>
</div>
  1. 在需要缓存的页面中,通过导航守卫 beforeRouteEnter 和 activated 钩子判断使用缓存还是重新渲染
beforeRouteEnter (to, from, next) {
    // 只在详情返回时做缓存
    if (from.name === 'detail') {
        to.meta.isKeep = true
    } else {
        to.meta.isKeep = false
    }
    next()
},
activated () {
    if(this.$route.meta.isKeep) {
        // 详情返回,取缓存数据
    } else {
        // 重新渲染,在这里调用加载请求
    }
}

此处 beforeRouteEnter 钩子也可以使用 watch 属性监听路由的变化:

watch: {
    $route(to, from) {
        //通过to/from.path判断是否是需要缓存的路径然后添加逻辑
    }
}
问题

从详情返回列表时正常,但当用户在详情页按 F5 刷新之后,再返回列表就不能保留离开之前的状态了,因为这时页面重载了。

解决办法:

在离开当前之前,将信息储存在 localStorage 中,当详情数据刷新后,手动触发加载请求。

5.参考文档

https://vue3js.cn/docs/zh/api/options-lifecycle-hooks.html#activated
https://www.cnblogs.com/wangjiachen666/p/11497200.html
https://www.cnblogs.com/dhui/p/13589401.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值