vuex页面刷新时数据丢失解决方案
- vuex 全局数据
- window.addEventListener("beforeunload",()=>{ }) 监听页面刷新
- 使用localStorage 临时存储数据
思路:在页面刷新的时候,将vuex中的数据存储到localstorage ,然后刷新结束后再将localstorage里的数赋值给store并清楚localstorage
代码
//js 监听页面alert刷新
window.addEventListener("beforeunload", () => {
localStorage.setItem("stateInfo", JSON.stringify(this.$store.state));
});
if (localStorage.getItem("stateInfo")) {
this.$store.replaceState(
Object.assign(
{},
this.$store.state,
JSON.parse(localStorage.getItem("stateInfo"))
)
);
}
localStorage.removeItem("stateInfo");
console.log("名字", this.$store.state);
还可以考虑使用 vuex-persistedstate 这个插件,具体使用可以上npm官网搜索了解。
如果我的内容能对你有所帮助,我就很开心啦!
浙公网安备 33010602011771号