一 持久化,刷新不丢失
采用插件 vuex-persistedstate
cnpm install vuex-persistedstate --save
// vuex-index.js
import createPersistedState from "vuex-persistedstate"
const debug = process.env.NODE_ENV !== 'production'
const createPersisted = createPersistedState({
// 默认在localStorage,可以自定义
storage: window.sessionStorage
})
export default new Vuex.Store({
plugins: debug ? [createLogger(), createPersisted] : [createPersisted]
})
二 递归重置 Vuex
// 新建common.js
export const clearVuexValue = (state) => {
if (!state) { return false }
Object.keys(state).forEach(key => {
if (typeof (state[key]) === 'object') {
clearVuexValue(state[key])
} else if (typeof (state[key]) === 'boolean') {
state[key] = false
} else if (Array.isArray(state[key])) {
state[key] = []
} else {
state[key] = ''
}
})
}
// mutations.js
import { clearVuexValue } from '@/utils/common.js'
setVuexState (state, clearVal = {}) {
clearVuexValue(state)
},
// 组件调用
// 方式一:
import store from '@/store/index'
store.commit('setVuexState')
// 方式二:
import { mapMutations } from 'vuex'
methods: {
...mapMutations({
setVuexState: 'setVuexState'
})
}