Vuex 突变调用另一个突变或同步动作?

Vuex mutation calling another mutation or a synchronous action instead?

我正在学习 Vuex,但在构建我的应用程序时遇到了问题。

考虑这些代码,它们都在做同样的事情:

示例 #1:

mutations: {
  add: function(state, employee) {
    state.employees.push(employee);
  },
  remove: function(state, index) {
    state.employees.splice(index, 1);
  }
},
actions: {
  generate: function(context) {
    context.commit('add', 'John Smith');
  }
}

如果操作应该是异步的,那么这是错误的。

示例 #2:

mutations: {
  add: function(state, employee) {
    state.employees.push(employee);
  },
  remove: function(state, index) {
    state.employees.splice(index, 1);
  },
  generate: function(state) {
    this.commit('add', 'John Smith');
  }
}

我可以从另一个突变中调用一个突变吗?如果不是,那就太不对了。

示例 #3:

mutations: {
  add: function(state, employee) {
    state.employees.push(employee);
  },
  remove: function(state, index) {
    state.employees.splice(index, 1);
  },
  generate: function(state) {
    state.employees.push('John Smith');
  }
}

另一方面,这重复了逻辑 - 这似乎是错误的!

示例 #4:

商店

mutations: {
  add: function(state, employee) {
    state.employees.push(employee);
  },
  remove: function(state, index) {
    state.employees.splice(index, 1);
  }
}

组件

methods: {
  addJohnSmith: function() {
    this.$store.commit('add', 'John Smith')
  },
}

这个看起来不错,但我认为这是正确的方法只有当所有输入都来自组件。如果我需要此功能由 store 控制,例如,如果我需要以某种方式转换此值怎么办?该组件应该足够笨,不关心这个。一个人为的例子可能是在员工姓名之前添加一个随机生成的头衔,因此最终结果如下所示:Mr John Smith。

哪一个是处理此问题的正确方法?

你的第一个例子是正确的结构。

确实,任何与 Vuex 模块相关的异步代码都应该保存在模块的操作中,而不是在其突变中。但是,操作 不需要 是异步的。

它们可以包含与模块相关的同步代码。这样,正如您在上一个示例中所说,引用 Vuex 模块的组件不需要知道该内部逻辑。