需求:
用户列表页面(user/list)做了大量的筛选,排序,分页等操作之后,点击用户姓名,进入用户详情页面(user/list/:id),浏览完详情信息之后,需要返回列表页面。此时,如果不做保留筛选条件或者分页条件,列表页面会呈现初始化状态,用户要得到之前的筛选结果页面,得重复大量工作,用户体验不好。
解决办法:
1:localstorage在用户进入详情子页面的时候,保留全部筛选条件,分页条件。再次进入列表页面的时候,从localstorage里面读取筛选条件,进行查询。 方案可行,但是对于整个项目类似的情况,各个页面都得加,麻烦,并且之后的可发工作可能会遗忘保留筛选条件
2: 使用vue的keep-alive内置组件,并且用mixin的方法注册到全局 方案可行,也不用各个页面都加,一劳永逸。 唯一一点就是列表和详情页面的path要对应
export default {
beforeRouterLeave: (to, from, next) => {
let toPath = to.path;
let fromPath = from.path;
if (toPath.startsWith(fromPath)){
from.meta.keepAlive = true;
} else {
from.meta.keepAlive = false;
}
next();
},
// 主要是消除从其他页面进入列表页面时的keepAlive
beforeRouterEnter: (to, from, next) => {
let toPath = to.path;
let fromPath = from.path;
if (!fromPath.startsWith(toPath)){
to.meta.keepAlive = false;
}
next();
}
}
mian.js中
import keepAlive from '@/minxins/keepAlive';
Vue.mixin(keepAlive)