The data in vuex store is stored in the running memory. When the page is refreshed, the page will reload the VUE instance, and the data in VUex will be reassigned. In this way, the data in VUex will be lost when the page is refreshed. How to solve the problem of losing browser refresh data?
Method 1: global listening, when the page is refreshed, store the value of state in the store to the sessionStorage, and then get from the sessionStorage, assign the value to the store, and remove the data in the sessionStorage. Add the following code to app.vue:
created() {
window.addEventListener('beforeunload'.() = >{
sessionStorage.setItem('list'.JSON.stringify(this.$store.state))
})
try{
sessionStorage.getItem('list') && this.$store.replaceState(Object.assign({},this.$store.state,JSON.parse(sessionStorage.getItem('list'))))}catch(err) {
console.log(err);
}
sessionStorage.removeItem("list");
}
Copy the code
Attention!!!!!! Storage can only store strings of data. Arrays or objects commonly used in JS cannot be directly stored. However, we can convert other data types to strings and store them in storage using the parse and Stringify methods provided by JSON objects.
Method 2: Install vuex-PersistedState
1. NPM install vuex-Persistedstate-s Add the following code to the store/index.js file: import persistedState from 'vuex-persistedstate' const store = new Vuex.Store({ state:{}, getters:{}, ... Plugins: [persistedState()] // add plugin})Copy the code
Attention!!!!!! By default, localStorage is used to store data by vuex-persistedstate.
In this case, you need to use sessionStorage for storage and modify the code in the plugins
plugins: [
persistedState({ storage: window.sessionStorage })
]
Copy the code