首先可以封装一个localstorage的公共方法,封装localstorage
然后在main.js中全局挂载(也可以在页面上单独引入)
import {
setLocalStorage,
getLocalStorage,
removeLocalStorage,
clearLocalStorage
} from "@/utils/localStorage";
//localStorage的挂载
Vue.prototype.setLocalStorage = setLocalStorage;
Vue.prototype.getLocalStorage = getLocalStorage;
Vue.prototype.removeLocalStorage = removeLocalStorage;
Vue.prototype.clearLocalStorage = clearLocalStorage;
页面:
//在页面离开之前,将搜索条件缓存起来
beforeRouteLeave(to, from, next) {
let query = {
queryParams: this.queryParams,
dateRange: this.dateRange
};
this.setLocalStorage("matter" + this.$route.query.eventStatus, query);
next();
},
//写在created或mounted中
//读取缓存的搜索条件
let query = this.getLocalStorage("matter" + this.$route.query.eventStatus);
if (query) {
this.queryParams = query.queryParams;
this.dateRange = query.dateRange;
}
在首页:
//清空所有的缓存
this.clearLocalStorage();