Vuejs:mapMutations

Nic*_*s B 3 vue.js vuex vuejs2

我是 Vues.js 的初学者,我在问一些关于 mapMutation 方法的问题。我想用这种方法传递参数,但我不知道如何。我想通过使用 mapMutations 来转换我的两种方法:

increment() {
   this.$store.commit(M_COUNT_INCREMENT, {
      amount: 1,
   });
},
decrement() {
   this.$store.commit(M_COUNT_DECREMENT, {
       amount: 1,
   });
},
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情,但传递我的“金额”参数:

...mapMutations({
   increment: M_COUNT_INCREMENT,
   decrement: M_COUNT_DECREMENT,
}),
Run Code Online (Sandbox Code Playgroud)

任何的想法 ?

谢谢

gta*_*ero 6

你当然可以做到!您可以将一个或多个参数传递给一个 mutator。您将不得不调整您的数据以匹配您的情况,但这是您实现它的方式:

您在 Vuex 存储对象中的修改器:

mutations: {
  increment (state, newValue) {
    state.counter = state.counter + newValue;
  },
  decrement (state, newValue) {
    state.counter = state.counter - newValue;
  }
}
Run Code Online (Sandbox Code Playgroud)

您的 Vue 方法中的地图 Mutator(未计算):

...mapMutations(['increment', 'decrement'])
Run Code Online (Sandbox Code Playgroud)

你的带有变异映射的新 setter:

this.increment(this.yourNumber); // Value 1 in your example
Run Code Online (Sandbox Code Playgroud)

就是这样!

奖金!您可以将许多变量(有效负载)传递给具有值对的变异函数;例如:

this.increment({
  id: this.counterId,
  newValue: this.newValue
});
Run Code Online (Sandbox Code Playgroud)

奖金2!你的突变器应该改变一点:

 mutations: {
  increment (state, payload) {
  state.selectedCounter[payload.id].counter = payload.newValue;
 }
}
Run Code Online (Sandbox Code Playgroud)

惊人的?阅读官方文档!https://vuex.vuejs.org/guide/mutations.html


小智 2

您本质上尝试的是用有效负载的参数来柯里化突变。

这对于 mapMutations() 来说是不可能的,它只将突变映射到方法 1:1,因为它们是这样的。

因此,您必须对这些实例使用初始方法。链接的答案: https://forum.vuejs.org/t/vuex-mapmutations/2455/3