vue 的 keep-alive 详解

发布于:2024-04-29 ⋅ 阅读:(39) ⋅ 点赞:(0)

目录

keep-alive 是什么?

keep-alive 属性

keep-alive 使用场景及用法

keep-alive 匹配规则

缓存实例的生命周期

缓存后如何获取数据

原理分析


keep-alive 是什么?

<KeepAlive> 是一个内置组件,它的功能是在多个组件间动态切换时缓存被移除的组件实例,而不是销毁它们,可防止重复渲染 DOM。

<keep-alive> 与 <transition>相似,只是一个抽象组件,它不会在 DOM 树中渲染(真实或者虚拟都不会),也不在父组件链中存在,比如:你在 this.$parent 中永远找不到 keep-alive 。

keep-alive 属性

属性名 属性值 描述
include 字符串或正则表达式 只有 name 匹配的组件会被缓存
exclude 字符串或正则表达式 任何 name 匹配的组件都不会被缓存
max 数字 最多可以缓存多少组件实例。

类似一个 LRU 缓存:如果缓存的实例数量即将超过指定的那个最大数量,则最久没有被访问的缓存实例将被销毁,以便为新的实例腾出空间

keep-alive 使用场景及用法

使用原则:当我们在某些场景下不需要让页面重新加载时我们可以使用 keep-alive

当我们从首页–>列表页–>商详页–>再返回,这时候列表页应该是需要 keep-alive

首页–>列表页–>商详页–>返回到列表页(需要缓存)–>返回到首页(需要缓存)–>再次进入列表页(不需要缓存),这时候可以按需来控制页面的 keep-alive

  • 普通用法
    <template>
        <div>
            <keep-alive include="test-keep-alive">
                <!-- 将缓存 name 为 test-keep-alive 的组件 -->
                <component></component>
            </keep-alive>
     
            <keep-alive include="a,b">
               <!-- 将缓存 name 为 a 或者 b 的组件,结合动态组件使用 -->
               <component :is="currentComponent"></component>
            </keep-alive>
     
            <!-- 使用正则表达式,需使用v-bind -->
            <keep-alive :include="/a|b/">
               <component :is="currentComponent"></component>
            </keep-alive>
     
            <!-- 动态判断 -->
            <keep-alive :include="includedComponents">
               <router-view></router-view>
            </keep-alive>
     
            <keep-alive exclude="test-keep-alive">
               <!-- 将不缓存 name 为 test-keep-alive 的组件 -->
               <component></component>
            </keep-alive>
        </div>
    </template>
    
    
    <scripts>
    export default {
      name: 'test-keep-alive',
      data () {
        return {
            includedComponents: "test-keep-alive",
            currentComponent: 'test-keep-alive'
        }
      },
     watch: {
        // 监听 currentComponent 的变化,动态决定是否需要缓存
        currentComponent(newComponent, oldComponent) {
          if (/* 某些条件 */) {
            this.includedComponents.push(newComponent);
          } else {
            this.includedComponents = [];
          }
        }
      }
    }
    </scripts>
  • 结合 router,缓存部分页面
    // 使用 $route.meta 的 keepAlive 属性
    <keep-alive>
        <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
    // 需要在 router 中设置 router 的元信息 meta
    //...router.js
    export default new Router({
      routes: [
        {
          path: '/',
          name: 'Hello',
          component: Hello,
          meta: {
            // 不需要缓存
            keepAlive: false 
          }
        },
        {
          path: '/page1',
          name: 'Page1',
          component: Page1,
          meta: {
            // 需要被缓存
            keepAlive: true 
          }
        }
      ]
    })
  • 当然,也可以通过动态设置 route.meta 的 keepAlive 属性来实现其他需求。例如:首页是A页面。B页面跳转到A,A页面需要缓存。C页面跳转到A,A页面不需要被缓存。
    // A 路由
    {
        path: '/',
        name: 'A',
        component: A,
        meta: {
            keepAlive: true // 需要被缓存
        }
    }
    // B页面
    export default {
        data() {
            return {};
        },
        methods: {},
        beforeRouteLeave(to, from, next) {
            // 设置下一个路由的 meta
            // B 跳转到 A 时,让 A 缓存,即不刷新
            to.meta.keepAlive = true;  
            next();
        }
    };

思路:在每个路由的 beforeRouteLeave(to, from, next) 钩子中设置 to.meta.keepAlive

keep-alive 匹配规则

  •  首先匹配组件的 name 选项
  •  如果 name 选项不可用,则匹配它的局部注册名称(父组件 components 选项的键值)
  •  匿名组件,不可匹配(路由组件没有 name 选项,并且没有注册的组件名)
  •  只能匹配当前被包裹的组件,不能匹配更下面嵌套的子组件,例如:只能匹配路由组件的 name 选项,不能匹配路由组件里面的嵌套组件 name 选项
  •  不会在函数式组件中正常工作,因为他们没有缓存实例
  •  exclude 的优先级 > include

缓存实例的生命周期

当一个组件实例从 DOM 上移除但因为被 <KeepAlive> 缓存而仍作为组件树的一部分时,它将变为不活跃状态而不是被卸载。当一个组件实例作为缓存树的一部分插入到 DOM 中时,它将重新被激活

注意:

  • 这两个钩子只有组件被 keep-alive 包裹时才会被调用
  • 在 2.1.0 版本之后,使用 exclude 排除之后,就算被包裹在 keep-alive 中,这两个钩子依然不会被调用
  • 在服务端渲染期间,这两个钩子也不会被调用
  • activated 在组件第一次渲染时会被调用,之后每次 keep-alive 被激活时调用
    // 第一次进入缓存路由/组件,在 mounted 后面,beforeRouteEnter 守卫传给 next 的回调函数之前
    beforeRouteEnter =>
    beforeCreate =>
    created =>
    beforeMount => 
    如果你是从别的路由/组件进来(组件销毁 destroyed/或离开缓存 deactivated) =>
    mounted => 
    activated 进入缓存组件 => 
    执行 beforeRouteEnter 回调
    
    // 因为组件被缓存了,再次进入缓存路由/组件时,不会触发这些钩子 beforeCreate create beforeMount mounted
    组件销毁destroyed /离开缓存 deactivated => 
    activated 进入当前缓存组件  => 
    执行 beforeRouteEnter 回调(组件缓存或销毁,嵌套组件的销毁和缓存也在这里触发)
    
  • deactivated 组件被停用(离开路由)时调用

    组件内的离开当前路由钩子 beforeRouteLeave =>  
    路由前置守卫 beforeEach =>
    全局后置钩子afterEach => 
    deactivated 离开缓存组件 => 
    activated 进入缓存组件(如果你进入的也是缓存路由)
    // 如果离开的组件没有缓存的话 beforeDestroy 会替换 deactivated 
    // 如果进入的路由也没有缓存的话  
    全局后置钩子 afterEach =>
    销毁 destroyed => 
    beforeCreate等

缓存后如何获取数据

解决方案可以有以下两种:

  • beforeRouteEnter:每次组件渲染的时候,都会执行 beforeRouteEnter

    beforeRouteEnter(to, from, next){
        next(vm=>{
            console.log(vm)
            // 每次进入路由执行
            vm.getData()  // 获取数据
        })
    },
  • actived:在keep-alive缓存的组件被激活的时候,都会执行actived钩子

    activated(){
       this.getData() // 获取数据
    },

原理分析

keep-alivevue中内置的一个组件

源码位置:src/core/components/keep-alive.js

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
      /* 获取组件的key值 */
      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
     /*  拿到key值后去this.cache对象中去寻找是否有该值,如果有则表示该组件有缓存,即命中缓存 */
      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
        /* 如果配置了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])
  }
}

可以看到该组件没有 template,而是用了 render,在组件渲染的时候会自动执行 render 函数

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

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

在组件销毁的时候执行 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 钩子函数中观测 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对象剔除即可

关于keep-alive的最强大缓存功能是在render函数中实现

首先获取组件的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,如果超过了,则把第一个缓存组件删掉