vue.js - 如何清除 vuex store 中的状态?

标签 vue.js vuejs2 vuex

我在 vuex store 中的状态很大。

有没有办法一次性重置所有状态的数据,而不是手动将所有数据设置为空?

最佳答案

我刚刚找到了适合我的绝佳解决方案。

const getDefaultState = () => {
  return {
    items: [],
    status: 'empty'
  }
}

// initial state
const state = getDefaultState()

const actions = {
  resetCartState ({ commit }) {
    commit('resetState')
  },
  addItem ({ state, commit }, item) { /* ... */ }
}

const mutations = {
  resetState (state) {
    // Merge rather than replace so we don't lose observers
    // https://github.com/vuejs/vuex/issues/1118
    Object.assign(state, getDefaultState())
  }
}

export default {
  state,
  getters: {},
  actions,
  mutations
}

感谢 Taha Shashtari 提供的出色解决方案。

迈克尔,

关于vue.js - 如何清除 vuex store 中的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42295340/

相关文章:

vuejs2 - vuetify组件的v-select文本如何居中对齐

javascript - 通过渲染函数实现的 v-model 不是响应式(Reactive)的

javascript - 使用 Vuex 的未知突变类型

vue.js - Vue组件的结构应该是什么?应该按什么顺序添加功能?

django - 服务器响应状态为 415(不支持的媒体类型) - vue.js 和 python django

javascript - Vue : Child string prop wont render

typescript - Vuex 不更新组件

vue.js - 从 vuex 和 Vue-native-websocket 插件接收 WebSockets 数据

javascript - Vue 不显示特定路线上的组件

javascript - VueJS : Building for production. ..杀死