-
Props:
include
-string | RegExp | Array
。只有名称匹配的组件会被缓存。exclude
-string | RegExp | Array
。任何名称匹配的组件都不会被缓存。max
-number | string
。最多可以缓存多少组件实例。
用法:
<keep-alive>
包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 <transition>
相似,<keep-alive>
是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在组件的父组件链中。
主要用于保留组件状态或避免重新渲染。
注意事项:
1. 优先级: 如果 `exclude` 和 `include` 内都有同个组件名, `exclude` 优先级高于 `include`
2. 缓存销毁: `max` 当已缓存的组件数量超过 `max` 值,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉。
3. 生命周期: 被缓存的组件才会调用 `activated` 这些缓存相关的生命周期 ,换句话说就是 `exclude` 内的组件不会触发 activated!!
4. 离开组件、再度激活: 当组件在 `<keep-alive>` 内被切换时,它的 mounted 和 unmounted 生命周期钩子不会被调用,取而代之的是 activated 和 deactivated。(这会运用在 `<keep-alive>` 的直接子节点及其所有子孙节点。)
使用案例:
<template>
<keep-alive :exclude="['test1']" :include="['test1','test2']" max='1'>
<component :is='dynamic'></component>
</keep-alive>
<el-button @click='changeComponent'>更改组件</el-button>
</template>
<script setup lang="ts">
import test1 from './test-components/test1.vue'
import test2 from './test-components/test2.vue'
import { ref,shallowRef } from 'vue'
let dynamic:any = shallowRef(test1)
let state = ref(true)
function changeComponent() {
if (state.value) {
dynamic.value = test2
}else{
dynamic.value = test1
}
state.value = !state.value
}
</script>
-
include
和exclude
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>
使用了 include / exclude 后,必须显式声明组件的 name !!!
这样才能与缓存组件匹配、生效。
注意,<keep-alive>
是用在其一个直属的子组件被切换的情形。如果你在其中有 v-for
则不会工作。如果有上述的多个条件性的子元素,<keep-alive>
要求同时只有一个子元素被渲染。
案例的<component :is="comp">动态组件在vue3的用法参见:
[深入vue2/3之动态组件]options与composition api的写法_oumae-kumiko的博客-CSDN博客
QQ交流群:522976012 ,欢迎来玩。
聚焦vue3,但不限于vue,任何前端问题,究其本质,值得讨论,研究与学习。