一.背景
由于业务需要,部分页面组件在页面跳转时需要缓存比如列表跳转到详情页面,需要缓存,列表之间的页面相互跳转时,就不需要缓存,特设计方案去满足这个业务需要,并在整个平台内进行推广。
二.适配步骤
1.在前端项目工程的路由入口组件例如(app.vue,下面用app.vue代表这个组件)中找到距离父组件最近的,
然后在它外层添加keep-alive组件
,
2.在app.vue组件的data中声明两个变量数组,需要组件的名称数组
cachedViews
和路由数组
history
,
3.在app.vue组件中用watch监听路由$route,然后在具体的路由里面将需要缓存的组件名称通过监听路由变量的方式逐步添加到cachedViews这个变量中,
同时由于浏览器自带的回退按钮,每次点击后退时就需要把之前的缓存组件从cachedViews中给去除掉,此时history就充当中间参照物的作用,具体代码如下
watch: {
$route(to, from) {
//处理缓存问题
const componentName =
to.matched[to.matched.length - 1].components.default?.name ??
"indexPage";
const history = this.history;
//后退
if (to.path === history[history.length - 2]) {
//处理回退时,缓存问题,历史回退需要重新把以前的缓存给清掉
this.cachedViews.splice(history.length - 1, 1);
this.history.splice(history.length - 1, 1);
} else {
//前进
if (
to.path.indexOf("/expertask") > -1 ||
to.path.indexOf("/taskcenter") > -1 ||
to.path.indexOf("/model") > -1 ||
to.path.indexOf("/bizmodel") > -1 ||
to.path.indexOf("/images") > -1 ||
to.path.indexOf("/myAbility") > -1 ||
to.path.indexOf("/publicAbility") > -1
) {
if (!this.cachedViews.includes(componentName)) {
this.cachedViews.push(componentName);
this.history.push(to.path);
}
}else {
this.cachedViews = [];
this.history = [];
}
}
},
},
4.在需要缓存的组件中,添加对应的组件名称,不需要缓存的组件不需要添加组件名称,注意组件名称要语义化,尽量不要和其他组件重复,否则可能会出现缓存的问题,
代码如下:name:"组件名称"
5.当一个
页面组件只需要缓存其中的一部分,另一部分需要刷新可以通过监听这个路由,只要路径发生改变时这一块的代码就重新再执行一遍,具体可以参考如下代码:
方案一:
watch: {
$route(to, from) {
if (from.name === "experTaskEdit") {//需要更新的条件
this.searchExperTask();//执行更新的代码
}else{
//不需要缓存的条件下,重置更新的代码
}
},
},
方案二
beforeRouteEnter(to, from, next) {
next((vm) => {
if (to.query.type === "machinetask") {//需要更新的条件
vm.taskType = "machinetask";//执行更新的代码
}
else{
//不需要缓存的条件下,重置更新的代码
}
});
},