在Vue單頁應用中,如果在某一個具體路由的具體頁面下點擊刷新,那么刷新后,頁面的狀態信息可能就會丟失掉。這時候應該怎么處理呢?如果你也有這個疑惑,這篇文章或許能夠幫助到你
在 App.vue
的 created
鈎子函數里寫下如下代碼:
-
//在頁面加載時讀取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))
-
})