解決vue刷新頁面以后丟失store的數據


刷新頁面時vue實例重新加載,store就會被重置,可以把定義刷新前把store存入本地localStorage、sessionStorage、cookie中,localStorage是永久儲存,重新打開頁面時會讀取上一次打開的頁面數據,sessionStorage是儲存到關閉為止,cookie不適合存大量數據。根據我的需求,最合適的是sessionStorage。
beforeunload在頁面刷新時觸發,可以監聽這個方法,讓頁面在刷新前存store到sessionStorage中。
當然,在頁面刷新時還要讀取sessionStorage中的數據到store中,讀取和儲存都寫在app.vue中。

export default {
  name: 'app',
  created () {
    // 在頁面加載時讀取sessionStorage
    if (sessionStorage.getItem('store')) {
      this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem('store'))))
    }
    // 在頁面刷新時將store保存到sessionStorage里
    window.addEventListener('beforeunload', () => {
      sessionStorage.setItem('store', JSON.stringify(this.$store.state))
    })
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM