Vue缓存策略
页面样式
需求1
从详情页返回列表页,需记录列表页的选择状态和页码
方案:使用localstorage或vuex实现
注:示例代码和业务可能存在依赖,这里只是提供思路
前提:列表页需要实现分页组件
首先在设置一个开关:openroute,实现灰度上线
props: {
openroute: {
type: Boolean,
default: () => (false)
}
}
在分页组件中存储选择条件和页码
let newPage;
//openroute处理
if (this.openroute) {
//缓存page
if (page) { //page存在则缓存page
localStorage.setItem("lastPath", location.href + "@" + page);
} else {
let lastPath = localStorage.getItem("lastPath");
if (lastPath && lastPath !== 'undefined' && lastPath.split('@')
&& lastPath.split('@')[0] === location.href) { //同一页面时的处理逻辑
let condition = localStorage.getItem("condition");
if (condition !== JSON.stringify(params.data)) { //选择条件变更则重置page
localStorage.setItem("lastPath", location.href + "@1");
} //选择条件未变更则保持page
} else { //未存储过数据 或者 页面地址发生变更 时则重置page
localStorage.setItem("lastPath", location.href + "@1");
}
}
//缓存condition
localStorage.setItem("condition", JSON.stringify(params.data));
//获取page
let lastPath = localStorage.getItem("lastPath");
if (lastPath && lastPath !== 'undefined' && lastPath.split('@') && lastPath.split('@')[1]) {
newPage = Number(lastPath.split('@')[1]);
} else {
newPage = 1;
}
} else {
newPage = page;
}
在列表页面打开开关,并且在created方法中读取存储的数据
u-pagination(@paginated="afterPagination", :params="pagination", :immediate.sync="pagination_immediate" :openroute="true")
//获取缓存的数据
let condition = localStorage.getItem("condition");
if (condition) {
Object.assign(this.form, JSON.parse(condition))
}
存在的问题
如果请求参数和template中显示的字段不同,会增加回显的工作量。