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

时间:2017-10-10 16:24:16

标签: vue.js state store vuex

我正在学习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 控制,例如,如果我需要以某种方式转换此值,该怎么办?该组件应该足够愚蠢,不关心这一点。一个人为的例子可能会在员工姓名之前添加一个随机生成的标题,因此最终结果如下:John Smith先生。

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

1 个答案:

答案 0 :(得分:3)

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

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

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