vue單頁面應用刷新網頁後vuex的state數據丟失的解決方案

app.vue入口組件中添加以下代碼,這樣就能夠保證每次刷新頁面均可以觸發vue

 1 export default {  2   name: 'App',  3  created () {  4     //在頁面加載時讀取sessionStorage裏的狀態信息
 5     if (sessionStorage.getItem("store") ) {
       //this.$store.replaceState()替換 store 的根狀態
6 this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store")))) 7 } 8 9 //在頁面刷新時將vuex裏的信息保存到sessionStorage裏 10 window.addEventListener("beforeunload",()=>{ 11 sessionStorage.setItem("store",JSON.stringify(this.$store.state)) 12 }) 13 } 14 }
相關文章
相關標籤/搜索