前言
最近遇到個(gè)問題,vue中vuex中的store數(shù)據(jù),會在頁面刷新后初始化,為了解決這一問題決定將store里面數(shù)據(jù)在頁面刷新前保存到sessionStorage,至于為何用他,因?yàn)轫撁骊P(guān)閉后他會被清空,localStorage則會一直存在,cookie又太小,因此sessionStorage最合適。
- 在app.vue的created方法中讀取sessionstorage中的數(shù)據(jù)存儲在store中,此時(shí)用vuex.store的replaceState方法,替換store的根狀態(tài)
- 在beforeunload方法中將store.state存儲到sessionstorage中。
代碼
export default {
name: 'app',
created () {
// 在頁面加載時(shí)讀取sessionStorage
if (sessionStorage.getItem('store')) {
this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem('store'))))
}
// 在頁面刷新時(shí)將store保存到sessionStorage里
window.addEventListener('beforeunload', () => {
sessionStorage.setItem('store', JSON.stringify(this.$store.state))
})
}
}