通常在vue项目中使用vuex做全局的状态管理,但是刷新之后,vuex中的数据会丢失
因为store是存储在运行内存中,当浏览器刷新时,会重新加载vue实例,store也会重新赋值
通常将一些数据保存在localstorage、sessionstorage或cookie中,可以保证页面刷新数据不丢失且易于读取。
vue项目一般操作都在同一个页面跳转路由,所以使用sessionstorage进行存储
直接在app.vue文件添加以下代码:
解决页面刷新vuex数据丢失问题
created() {
if (localStorage.getItem("store")) {
this.$store.replaceState(
Object.assign({}, JSON.parse(localStorage.getItem("store")))
);
}
window.addEventListener("beforeunload", () => {
localStorage.setItem("store", JSON.stringify(this.$store.state));
});
},