Problem Description
Vuex can perform global state management, but the data will disappear after refreshing, which is what we don't want to see. How to solve it, we can combine local storage to achieve data persistence, or through the plug-in -vuex-persistedstate.
question:
Use localStroge and sessionStroge, although data can be saved, but data can not be synchronized
. Although vuex can maintain data synchronization, the page refresh data is gone, because it has no real data storage function.
Use vuex-persistedstate to solve
Download the vuex-persistedstate plugin on the command line
npm install vuex-persistedstate --save
复制代码
Introduction and configuration
import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
// ...
plugins: [createPersistedState()]
})
复制代码
Stored to localStorage by default
Want to store to sessionStorage, the configuration is as follows
import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
// ...
plugins: [createPersistedState({
storage: window.sessionStorage
})]
})
复制代码
I want to use cookies in the same way to
persist all state by default
Specify the state that needs to be persisted, the configuration is as follows
import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
// ...
plugins: [createPersistedState({
storage: window.sessionStorage,
reducer(val) {
return {
// 只储存state中的assessmentData
assessmentData: val.assessmentData
}
}
})]
Vuex refers to the writing of multiple plug-ins
For example: vuex prompt plug-in and persistent plug-in are used together, the configuration is as follows
import createPersistedState from "vuex-persistedstate"
import createLogger from 'vuex/dist/logger'
// 判断环境 vuex提示生产环境中不使用
const debug = process.env.NODE_ENV !== 'production'
const createPersisted = createPersistedState({
storage: window.sessionStorage
})
export default new Vuex.Store({
// ...
plugins: debug ? [createLogger(), createPersisted] : [createPersisted]
})
If plugins is a one-dimensional array, it will parse errors
. Reprint: https://juejin.cn/post/6844903821588578312