美文网首页
vue页面刷新数据丢失问题

vue页面刷新数据丢失问题

作者: 前端召唤师 | 来源:发表于2019-04-26 12:05 被阅读0次

    参考: https://blog.csdn.net/aliven1/article/details/80743470
    https://blog.csdn.net/liang377122210/article/details/78880438
    https://blog.csdn.net/goodaxuan/article/details/82113123

    main.js文件中:

    
    var store = new Vuex.Store({
    
    state: {
    
    userMsg: ' '
    
    },
    
    getters: {
    
    },
    
    mutations: {
    
    set_userMsg(state, data) {
    
    state.userMsg = data
    
    }
    
    },
    
    actions: {
    
    },
    
    modules: {}
    
    })
    
    var data = {id:1, name:'王五'};
    
    this.$store.commit('set_userMsg', data);
    
    

    App.vue中:

    
    created() {
    
    //在页面加载时读取sessionStorage里的状态信息
    
    if(sessionStorage.getItem("userMsg")) {
    
    this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem("userMsg"))))
    
    }
    
    //在页面刷新时将vuex里的信息保存到sessionStorage里
    
    window.addEventListener("beforeunload", () => {
    
    sessionStorage.setItem("userMsg", JSON.stringify(this.$store.state))
    
    })
    
    }
    
    

    调用数据组件中:

    
    data         userMsg = ' ';
    
    method    let t = sessionStorage.getItem("userMsg");
    
                    let obj = JSON.parse(t);
    
                   this.userMsg = obj.userMsg;
    
                   console.log('userMsg', this.userMsg);     => userMsg   {id:1, name:'王五'}
    
    

    相关文章

      网友评论

          本文标题:vue页面刷新数据丢失问题

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