一、store數據丟失
系統登錄后獲取到系統菜單列表存入store中,發現在刷新頁面之后,store中的菜單數據丟失了。
console打印數據
刷新頁面之前
刷新頁面之后
二、原因
刷新頁面時,vue實例重新加載,從而,store也被重置了。store是用來存儲組件狀態的,而不是用來做本地數據存儲的。所以,對於不希望頁面刷新之后被重置的數據,使用本地存儲來進行存儲。
三、本地存儲
cookie: 不適合存儲大量的數據。
localStorage: 是永久存儲,瀏覽器關閉后數據不會丟失,除非主動刪除數據。當關閉頁面后重新打開,會讀取上一次打開的頁面數據。
sessionStorage: 在當前瀏覽器窗口關閉后自動刪除。所以,sessionStorage 最合適。
四、解決方法
監聽 beforeunload 這個方法,beforeunload 在頁面刷新時觸發,監聽 beforeunload 讓頁面在刷新前將數據存到 sessionStorage 中。然后,在頁面刷新時,讀取 sessionStorage 中的數據到 store 中。
代碼如下:
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
// 入口組件
export default {
name: 'App',
created() {
// 在頁面加載時讀取sessionStorage里的狀態信息
if (sessionStorage.getItem('store')) {
this.$store.replaceState(
Object.assign(
{},
this.$store.state,
JSON.parse(sessionStorage.getItem('store'))
)
)
}
// 在頁面刷新時將vuex里的信息保存到sessionStorage里
// beforeunload事件在頁面刷新時先觸發
window.addEventListener('beforeunload', () => {
sessionStorage.setItem('store', JSON.stringify(this.$store.state))
})
},
}
</script>