我用的方法很簡單,在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))
})
},