首页 文章

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

提问于
浏览
1

我正在学习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')
  },
}

这个似乎没问题,但我认为只有当所有输入都来自组件时,这才是正确的方法 . 如果我要求商店控制此功能,例如,如果我需要以某种方式转换此值,该怎么办?该组件应该足够愚蠢,不关心这一点 . 一个人为的例子可能会在员工姓名之前添加一个随机生成的 Headers ,因此最终结果如下:John Smith先生 .

哪一个是正确的处理方式?

1 回答

  • 3

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

    它是's true that any asynchronous code related to your Vuex module should be held in the module'的行动,而不是它的突变 . 但是,动作不需要是异步的 .

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

相关问题