vuex-persistedstate实现vuex持久化
vuex-index.js,更多用法vuex-persistedstate
插件使用
cnpm install vuex-persistedstate --save
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'
})
}
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。