vuex刷新頁面是store被更新,如何解決數據備份?

 我用的方法很簡單,在App.vue中的生命週期函數created中,監聽頁面刷新,在頁面刷新的時候,將store的數據及時存儲在sessionStorage中,然後刷新完畢後就可以將sessionStorage中的數據再取出來用

 

created () {  //頁面刷新store數據備份
    if (localStorage.cmstoken) {
      this.$router.replace("/data");
    }else {
      this.$router.replace("/");
    }
    if (sessionStorage.getItem("store") ) { //在頁面加載時讀取sessionStorage裏的狀態信息
        this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store"))))
    }
    window.addEventListener("beforeunload",()=>{ //在頁面刷新時將vuex裏的信息保存到sessionStorage裏
        sessionStorage.setItem("store",JSON.stringify(this.$store.state))
    })
  },

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章