Solution of Data Loss Caused by vuex Page Refresh

  • 2021-10-13 06:28:44
  • OfStack

Solve the problem of data loss caused by vuex page refresh

vuex data is stored in memory, and vuex data will naturally be lost after the page is refreshed. We have two ways to solve this problem:
1. Use vuex-along
2. Use localStorage or sessionStroage

1. Use vuex-along

The essence of vuex-along is to store the data in vuex into localStorage or sessionStroage, but this component will help us complete this access process. We only need to use vuex to read data, and simply understand the use of vuex-along under 1.

Install vuex-along:


npm install vuex-along --save

Configure vuex-along: Add the following code at the end of store/index. js:


import VueXAlong from 'vuex-along' // Import plug-ins 

export default new Vuex.Store({
  //modules: {
    //controler // Modularization vuex
  //},
  plugins: [VueXAlong({
    name: 'store',   // Store in localStroage Or sessionStroage  The name in 
    local: false,   // Whether it is stored in local Medium  false  Do not store   If stored, follow the following session Configuration of 
    session: { list: [], isFilter: true } // If the value is not false  You can pass the object   Among them   When isFilter Set to true When,  list  The values in the array are filtered , These values are not stored in the seesion Or local Medium 
  })]
});

2. Use localStorage or sessionStroage


created() {
  // Read when the page loads sessionStorage Status information in 
  if (sessionStorage.getItem("store")) {
   this.$store.replaceState(
    Object.assign(
     {},
     this.$store.state,
     JSON.parse(sessionStorage.getItem("store"))
    )
   );
  }
  // When the page is refreshed, the vuex Save the information in to sessionStorage Li 
  window.addEventListener("beforeunload", () => {
   sessionStorage.setItem("store", JSON.stringify(this.$store.state));
  });
},

The above two methods can solve the problem of data loss caused by vuex page refresh. After configuring according to the above method, vuex can be used normally, and the page refresh data will not be lost.

The above is the vuex page refresh caused by data loss solution details, more information about vuex data loss please pay attention to other related articles on this site!


Related articles: