简单学习Keep-alive

134 阅读3分钟

前言

大家好我是肥佬,在看到vue中有很多使用到Keep-alive组件的地方,但是一直搞不懂这是一个什么东西,只是简单的了解一个缓存啥啥啥的,今天来记录一下学习,希望各位指导指导

Keep-alive是个什么东西

keep-alive是vue里面的内置组件,能在组件切换过程中将状态保留在内存里,防止DOM重复渲染,它包裹动态组件时,会缓存不活动的组件,不会去销毁

keep-alive中有几个props:

  • include------可set字符串or正则表达式,符合匹配的会被缓存
  • exclude------可set字符串or正则表达式,符合匹配的都不会被缓存
  • max----------可set数字,最多可以缓存多少个组件

用法

普通用法:

<keep-alive>
    <xxx :data="data"></xxx>
</keep-alive>

使用include、exclude

<keep-alive include="string1,string2">
    <xxx :data="data"></xxx>
</keep-alive>

// 使用正则表达式
<keep-alive :include="/string1|string2/">
    <xxx :data="data"></xxx>
</keep-alive>

// 使用数组
<keep-alive :include="['string1','string2']">
    <xxx :data="data"></xxx>
</keep-alive>

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

设置了 keep-alive 缓存的组件,会多出两个生命周期钩子(activated与deactivated)

首次进入组件,mouted后执行activated,beforeRouteLeave后执行deactivated。二次进入时候beforeRouteEnter后执行activated,beforeRouteLeave后执行deactivated

使用的场景

当我们在某些场景下不需要让页面重新加载时我们可以使用keep-alive 在路由中设置keepAlive

{
  path: xxx,
  name: xxx,
  component (resolve) {
    require(['xxx/xxx/xxx'], resolve)
 },
 meta: {
  keepAlive: true,
  title: xxx
 }
}

<div id="app">
    <keep-alive>
        <router-view v-if="$route.meta.keepAlive"></router-view>
     </keep-alive>
     <router-view v-if="!$route.meta.keepAlive"></router-view>
</div>

结合源码简单理解原理

源码位置:src/core/components/keep-alive.ts 源码地址:github.com/vuejs/vue/b…

源码就不copy上来了。

打开源码可以看到keep-alive组件没有template,而是用了render,组件渲染时候会自动执行函数

源码中储存组件使用了this.cache对象

// 储存的形式
this.cache = {
    'key1':'组件1',
    'key2':'组件2',
}

在组件销毁的时候执行pruneCacheEntry函数

function pruneCacheEntry(
  cache: CacheEntryMap,
  key: string,
  keys: Array<string>,
  current?: VNode
) {
  const entry = cache[key]
  if (entry && (!current || entry.tag !== current.tag)) {
    // @ts-expect-error can be undefined
    entry.componentInstance.$destroy()
  }
  cache[key] = null
  remove(keys, key)
}

在mounted钩子函数中观测 include 和 exclude 的变化

mounted() {
    this.cacheVNode()
    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: { cache: CacheEntryMap; keys: string[]; _vnode: VNode },
  filter: Function
) {
  const { cache, keys, _vnode } = keepAliveInstance
  for (const key in cache) {
    const entry = cache[key]
    if (entry) {
      const name = entry.name
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

函数内对this.cache对象进行遍历,取出每一项的name值,用它和新的缓存规则进行匹配,如果匹配不上,则表示在新的缓存规则下该组件已经不需要被缓存,则调用pruneCacheEntry函数将其从this.cache对象剔除即可

render函数实现缓存功能

获取key值

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

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

if (cache[key]) {
    vnode.componentInstance = cache[key].componentInstance
    remove(keys, key)
    keys.push(key)
}

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

this.vnodeToCache = vnode
this.keyToCache = key

表明该组件还没有被缓存过,则以该组件的key为键,组件vnode为值,将其存入this.cache中,并且把key存入this.keys中

此时再判断this.keys中缓存组件的数量是否超过了设置的最大缓存数量值this.max,如果超过了,则把第一个缓存组件删掉

缓存后如何获取数据

可以在两个生命周期钩子解决: beforeRouteEnter activated

beforeRouteEnter

每次组件渲染都会执行

beforeRouteEnter(to, from, next){
    next(vm=>{
        vm.xxx()
    })
},

activated

在keep-alive缓存的组件被激活的时候,都会执行actived钩子

activated(){
    this.xxx()
},

pspspspsps!!! 服务器端渲染期间activated不被调用