The main role of VUEX is communication between components and centralized management of data.

However, since the data in VUex is stored in running memory, when we refresh the page, the data in store will be cleared.

How to solve this problem?

We can store data in a store using traditional storage methods, such as cookies, localStorage, or sessionStorage, and refresh the page without losing the data.

We used sessionStorage just to keep the data before the browser refresh, so that when the browser is closed, the storage will be cleared and no duplicate data will be generated.

The idea is that we listen for page refresh events and store data in sessionStorge before the refresh. Read the value in sessionStorage and assign it to store each time you enter the page, thus preserving the data before the refresh.

export default {
  name: 'App',
  created () {
    if (sessionStorage.getItem("store")) {// Read the status information in sessionStorage before page loading
     this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store"))))}window.addEventListener("beforeunload", () = > {// Save vuex information to sessionStorage before page refreshsessionStorage.setItem("store".JSON.stringify(this.$store.state))
    })
  }
}Copy the code