解決vue刷新頁面以后丟失store的數(shù)據(jù)

前言

最近遇到個(gè)問題,vue中vuex中的store數(shù)據(jù),會在頁面刷新后初始化,為了解決這一問題決定將store里面數(shù)據(jù)在頁面刷新前保存到sessionStorage,至于為何用他,因?yàn)轫撁骊P(guān)閉后他會被清空,localStorage則會一直存在,cookie又太小,因此sessionStorage最合適。

  1. 在app.vue的created方法中讀取sessionstorage中的數(shù)據(jù)存儲在store中,此時(shí)用vuex.store的replaceState方法,替換store的根狀態(tài)
  2. 在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))
    })
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容