頁面刷新後,原有的 vuex 中的 state 會發生改變,若是在頁面刷新以前,能夠將 state 信息保存,頁面從新加載時,再將該值賦給 state,那麼該問題便可解決。vue
可使用 localstorage 來保存信息。vuex
【在某組件中添加以下鉤子函數。好比 App.vue中】
created() {
//在頁面加載時讀取localStorage裏的狀態信息
if (localStorage.getItem("store") ) {
this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(localStorage.getItem("store"))))
}
//在頁面刷新時將vuex裏的信息保存到localStorage裏
window.addEventListener("beforeunload",()=>{
localStorage.setItem("store",JSON.stringify(this.$store.state))
})
}
注:
this.$store.replaceState() 用於替換 store 的信息(狀態合併)。
Object.assign(target, ...source) 將source的值 賦給 target,如有重複的數據,則覆蓋。其中...表示能夠多個source。
JSON.stringify() 用於將對象轉爲 JSON
JSON.parse() 用於將 JSON 轉爲對象
注意:
如有兩個組件,當調用 localstorage 的值,可能會出現問題。
以下圖,Main.vue 中 每次刷新頁面會 觸發 localstorage 操做。
開始 localstorage 中沒值,某用戶經過 Login.vue 組件 進入 Main.vue 組件並刷新頁面後,localStorage 會記錄當前用戶相關的 state 信息。
直接在瀏覽器中切換路徑到Login.vue。當另一個用戶經過 Login.vue 並進入 Main.vue 時,此時獲取的就是上一個用戶的信息,這樣確定會出問題(我遇到的一個坑,大體意思就是這樣)。瀏覽器
一個暴力的解決思路,在Login.vue中 直接將上一個用戶緩存的信息給刪除。
此時 localStorage 沒有了上個用戶的信息。
【Login.vue】
created() {
// 進入畫面前,移除主頁面保存的 state 信息
localStorage.removeItem("store")
}
而後只在Main組件刷新時 使用 localStorage 記錄信息。
【Main.vue】
created() {
//在頁面加載時讀取localStorage裏的狀態信息
if (localStorage.getItem("store") ) {
this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(localStorage.getItem("store"))))
}
//在頁面刷新時將vuex裏的信息保存到localStorage裏
window.addEventListener("beforeunload",()=>{
localStorage.setItem("store",JSON.stringify(this.$store.state))
})
}
也可使用 sessionStorage 來保存信息。緩存
【在某組件中添加以下鉤子函數。好比 App.vue中】
created() {
//在頁面加載時讀取sessionStorage裏的狀態信息
if (sessionStorage.getItem("store") ) {
this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store"))))
}
//在頁面刷新時將vuex裏的信息保存到sessionStorage裏
window.addEventListener("beforeunload",()=>{
sessionStorage.setItem("store",JSON.stringify(this.$store.state))
})
}
(1)localstorage 與 sessionStorage 都是客戶端用於存儲數據的。
(2)localStorage是沒有失效時間的,sessionStorage的聲明週期是瀏覽器的生命週期。
(3)當瀏覽器關閉時,sessionStorage的數據將清空,而localStorage數據只要不經過代碼特地的刪除或手動刪除,是永久保存的。
(4)若想清除localstorage 的數據。session
localStorage.removeItem(key) 清除一條數據
localStorage.clear() 清除所有的數據