美文网首页
解决页面刷新时 Vue 的状态(Vuex)数据丢失问题

解决页面刷新时 Vue 的状态(Vuex)数据丢失问题

作者: 酷酷的凯先生 | 来源:发表于2020-08-24 16:11 被阅读0次

Vue 状态在页面刷新时, 会丢失
解决: 在页面刷新时把状态数据保存在状态里, 举个栗子:

//-- 全局监听,页面刷新的时候将store里state的值存到sessionStorage中,
//-- 然后从sessionStorage中获取,再赋值给store。
//-- 然后再把session里面存的删除即可,相当于中间件的作用。
//-- 在页面加载时读取sessionStorage里的状态信息
if (sessionStorage.getItem("store")) {
    this.$store.replaceState(
        Object.assign(
            {},
            this.$store.state,
            JSON.parse(sessionStorage.getItem("store"))
        )
    );
    this.$store.commit('showErrorInfo',null);
}
//在页面刷新时将vuex里的信息保存到sessionStorage里
window.addEventListener("beforeunload", () => {
    sessionStorage.setItem("store", JSON.stringify(this.$store.state));
});

相关文章

网友评论

      本文标题:解决页面刷新时 Vue 的状态(Vuex)数据丢失问题

      本文链接:https://www.haomeiwen.com/subject/yqmnjktx.html