【问题标题】:Vuex mutation calling another mutation or a synchronous action instead?Vuex 突变调用另一个突变或同步操作?
【发布时间】:2018-03-22 03:25:09
【问题描述】:

我正在学习 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 先生。

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

【问题讨论】:

    标签: vue.js state store vuex


    【解决方案1】:

    您的第一个示例是正确的结构。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-30
      • 2017-01-21
      • 2017-01-10
      • 2019-09-03
      • 2019-10-07
      • 2019-03-08
      • 1970-01-01
      相关资源
      最近更新 更多