上份工作也遇到了这个问题,但没仔细研究,新入职的公司测试要求比较高,今天仔细看了下,百度了半天,没百度到合适的,自己动手丰衣足食了,终于在下班时搞出来了,真是也太开心啦~~
使用keep-alive 组件缓存,vue3中在APP.vue的写法:
<router-view v-slot="{ Component }">
<keep-alive :exclude="aliveComponent">
<component :is="Component" />
</keep-alive>
</router-view>
用eventBus 事件总线来控制组件是否需要缓存:
//引入了插件,注意全局只能使用同一个emitter
import mitt from 'mitt'
export const emitter = mitt()
默认所有页面都进行缓存,用:exclude="aliveComponent" ,排除不需要缓存的组件,可以实现动态更改组件是否缓存
aliveComponent: "NewQueue,ReleaseSet" //不需要缓存的组件页面名
// 添加不缓存组件
function setNotAliveComponent(keyword: String) {
let aliveItems = datas.aliveComponent;
aliveItems =
keyword +
"," +
aliveItems
.split(",")
.filter((e: String) => e != keyword)
.join(",");
if (aliveItems.substr(aliveItems.length - 1, 1) == ",") {
aliveItems = aliveItems.substring(0, aliveItems.length - 1);
}
datas.aliveComponent = aliveItems;
}
// 移除不缓存组件
function removeNotAliveComponent(keyword: String) {
let aliveItems = datas.aliveComponent;
let arr: Array<string> = aliveItems.split(",");
arr.filter((e: String, index: number) => {
if (e == keyword) {
arr.splice(index, 1);
}
});
aliveItems = arr.join(",");
datas.aliveComponent = aliveItems;
}
//接收 添加 不缓存组件 事件
emitter.on("add-no-alive-compt", (e) => {
setNotAliveComponent(e);
});
//接收 移除 不缓存组件 事件
emitter.on("remove-no-alive-compt", (e) => {
removeNotAliveComponent(e);
});
然后,在需要缓存的页面中触发事件
// 在不需要组件缓存时,比如在后退按钮中 添加 【不需要缓存组件】
emitter.emit("add-no-alive-compt", "Queue");
// 在需要组件缓存时,比如在前进页面前 移除 【不需要缓存组件】
emitter.emit("remove-no-alive-compt", "Queue");
这里主要是混合开发中的H5,如果后退使用到浏览器自带的后退功能,要结合路由来判断当前页面是否后退来进行触发添加 是否缓存事件了。