After the page refreshes, the page you want to save unsaved data. We always used to put sessionStorage and localStorage browser. But after using a vue, vuex can be applied.
vuex advantage: Compared sessionStorage, store data more secure, sessionStorage can be seen in the console.
vuex disadvantage: After F5 to refresh the page, vuex will re-update state, so that the stored data will be lost.
To overcome this problem, vuex-persistedstate appeared ~~
principle:
- The vuex of state presence localStorage or a cookie or a sessionStorage
- Instant refresh the page, vuex data disappear, vuex back sessionStorage in which data will disguise achieved without loss of data refresh
Instructions:
- installation:
npm install vuex-persistedstate --save
- Introducing and arranged
in the store under index.js
import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
// ...
plugins: [createPersistedState()]
})
Want to store to sessionStorage, configuration is as follows :
import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
// ...
plugins: [createPersistedState({
storage: window.sessionStorage
})]
})
Similarly cookie or want to use localStorage
vuex-persistedstate all persistent default state, specify the required persistent state, configuration is as follows :
import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
// ...
plugins: [createPersistedState({
storage: window.sessionStorage,
reducer(val) {
return {
// 只储存state中的user
user: val.user
}
}
})]
Val at the moment corresponds store / modules folder contents of several js file storage, which is stor / index in the import of nine modules, like the data on which part of the persistent storage, the name of the data in this configuration can be, now I just want to persistent data stored user module. Folder Contents are as follows:
Note: If you want to configure a number of options at the moment, will plugins written as a one-dimensional array, or will be error.
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]
})