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'
    })
}