1. 在app.vue中加入组件
官方文档:https://v3.cn.vuejs.org/api/built-in-components.html#keep-alive
//Vue2
<keep-alive>
<router-view/>
</keep-alive>
//Vue3
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>
2. keep-alive 属性
属性 | 类型 | 备注 |
---|---|---|
include | string 、RegExp 、 Array | 只有名称匹配的组件会被缓存,名称为组件的name值 |
exclude | string 、RegExp 、 Array | 任何名称匹配的组件都不会被缓存,名称为组件的name值 |
max | number 、 string | 最多可以缓存多少组件实例 |
3. 例子
- include、exclude
exclude与include参数类型一致
//string 多个用逗号分割
<keep-alive include="a,b,c">
//RegExp 正则匹配
<keep-alive :include="/a|b|c/">
//Array
<keep-alive :include="['a','b','c']">
- max
<keep-alive max="5">
Tip
1.组件名必须与include、exclude配置的名字一致
2.如果使用setup语法糖的时候name默认为文件名,如:Hello.vue,name为Hello
3.被缓存的组件切换时会执行activated和deactivated这两个钩子函数