Vuex can perform global state management, but after refreshing, data will disappear, which we do not want to see. To solve this problem, we can use local storage to persist data, or we can use vuex-PersistedState.

1. Manually leverage HTML5’s local storage

methods
  • Vuex state can be localStorage, sessionStorage, or other storage modes
  • Mutations, the definition of the method for vuex state operation and the corresponding operation for storage. The state then exists with the storage and synchronizes with vuEX
The problem
  • And the intuitive thing is, it’s a little bit cumbersome to write manually.

2. Use vuex-PersistedState

In fact, the principle of plug-in is also combined with the storage method, but unified configuration does not need to manually write storage method every time

Method of use
The installation
npm install vuex-persistedstate --save
Copy the code
Import and Configuration

In index.js under store

import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()]
})
Copy the code

The default storage is localStorage

To store to sessionStorage, configure as follows

import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState({
      storage: window.sessionStorage
  })]
})
Copy the code
Same thing if you want to use cookies

All states are persisted by default

Specify the state to persist, as follows

import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState({
      storage: window.sessionStorage,
      reducer(val) {
          return{// store only the state assessmentData assessmentData: val.assessmentData}}})]Copy the code

Vuex references multiple plug-in writing

For example, the vuex prompt plug-in is used with the persistent plug-in, and the configuration is as follows

import createPersistedState from "vuex-persistedstate"
import createLogger from 'vuex/dist/logger'Const debug = process.env.node_env! = ='production'
const createPersisted = createPersistedState({
  storage: window.sessionStorage
})
export default new Vuex.Store({
 // ...
  plugins: debug ? [createLogger(), createPersisted] : [createPersisted]
})
Copy the code

Plugins parse incorrectly if they are a one-dimensional array