Solve the problem of data loss after vuex refresh

Question: When we write vue projects, we often use vuex as memory to store, but the data we store in vuex (user data, current page data, etc.) will be lost after refreshing, so how to solve it ? super easy. Here everyone recommends this persistent plugin vuex-persistedstate. He can automatically store for you

Here's how to use it:

1. Install vuex-persistedstate

npm install --save vuex-persistedstate

2. Modify store.js

import createPersistedState from 'vuex-persistedstate'
 
const store = new Vuex.Store({
  state: {
    user: {}, //用户
  },
  mutations: {
    update_user(state, newuser) {
      state.user = newuser
    },
  },
    //把所有数据缓存到本地-(默认是存储到localStorage里的)
  plugins: [createPersistedState()],
})
 
export default store;

The above is stored in localStorage, so it can also be stored in session

import createPersistedState from 'vuex-persistedstate'
export default new Vuex.Store({
    。。。
  plugins: [createPersistedState({
    storage: window.sessionStorage
    })]
})

 

Guess you like

Origin blog.csdn.net/ShIcily/article/details/109026388