Tag Archives: the data of store is lost after refreshes

How to Fix “the data of store is lost after Vue refreshes the page”

When the page is refreshed, the VUE instance is reloaded, and the store will be reset. The store can be stored in the local localStorage, sessionStorage and cookie before the definition is refreshed. The localStorage is permanent storage, and the page data that was opened last time will be read when the page is reopened. According to my needs, the most appropriate is sessionStorage.
before upload fires when the page is refreshed. You can listen to this method to store the page to sessionStorage before the page is refreshed. Even when page refresh
of course, read the sessionStorage data into the store, read and stored, are written in the app. Vue.

export default {
  name: 'app',
  created () {
    // Read sessionStorage on page load
    if (sessionStorage.getItem('store')) {
      this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem('store'))))
    }
    // Save the store to sessionStorage when the page is refreshed
    window.addEventListener('beforeunload', () => {
      sessionStorage.setItem('store', JSON.stringify(this.$store.state))
    })
  }
}