vue單頁應用如何在頁面刷新時保留state狀態數據

在Vue單頁應用中,若是在某一個具體路由的具體頁面下點擊刷新,那麼刷新後,頁面的狀態信息可能就會丟失掉。這時候應該怎麼處理呢?若是你也有這個疑惑,這篇文章或許可以幫助到你

App.vuecreated 鉤子函數裏寫下以下代碼:vue

  • //在頁面加載時讀取localStorage裏的狀態信息
  • localStorage.getItem( "userMsg") && this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("userMsg"))));
  •  
  • //在頁面刷新時將vuex裏的信息保存到localStorage裏
  • window.addEventListener("beforeunload",()=>{
  • localStorage.setItem( "userMsg",JSON.stringify(this.$store.state))
  • })
相關文章
相關標籤/搜索