Vuejs : mapMutations
Solution 1
Sure you can do that! You can pass to a mutator one o many parameters. You will have to adjust your data to match your case, but this is the way you'll achieve it:
Your mutators inside VUEX store object:
mutations: {
increment (state, newValue) {
state.counter = state.counter + newValue;
},
decrement (state, newValue) {
state.counter = state.counter - newValue;
}
}
Your map Mutator inside your Vue METHODS (not computed):
...mapMutations(['increment', 'decrement'])
Your new setter with mutation mapping:
this.increment(this.yourNumber); // Value 1 in your example
THAT'S IT!
BONUS! You can pass many variables (payload) to a mutation function with value pairs; for example:
this.increment({
id: this.counterId,
newValue: this.newValue
});
BONUS2! And your mutator should change a bit:
mutations: {
increment (state, payload) {
state.selectedCounter[payload.id].counter = payload.newValue;
}
}
Amazing? Read the oficial doc! https://vuex.vuejs.org/guide/mutations.html
Solution 2
What you are essentially trying is currying the mutation with an argument for the payload.
That is not possible with mapMutations(), which only maps the mutations to methods 1:1, as they are.
So you will have to use the initial way for those instances. the answer from the link: https://forum.vuejs.org/t/vuex-mapmutations/2455/3
Solution 3
Your parameter, as of 2021 in Vue 3, is already being passed.
It's just a matter of calling/using the code in the right way:
increment() {
this.$store.commit(M_COUNT_INCREMENT, {
amount: 1,
});
},
decrement() {
this.$store.commit(M_COUNT_DECREMENT, {
amount: 1,
});
},
Will turn into this with mapMutations:
methods: {
...mapMutations([M_COUNT_INCREMENT,M_COUNT_DECREMENT]),
},
Then wherever you used increment() or decrement() in your templates or scripts:
Use:
M_COUNT_INCREMENT(payload)
M_COUNT_DECREMENT(payload)
For more info go to: https://next.vuex.vuejs.org/guide/mutations.html#committing-mutations-in-components
Nicolas B
Updated on June 14, 2022Comments
-
Nicolas B almost 2 years
I'm beginner with Vues.js and i'm asking something about mapMutation method. I want to pass parameters with this method but i don't know how. I want to transform my two methods by using mapMutations :
increment() { this.$store.commit(M_COUNT_INCREMENT, { amount: 1, }); }, decrement() { this.$store.commit(M_COUNT_DECREMENT, { amount: 1, }); },
I want do thing like this but with passing my "amount" parameter :
...mapMutations({ increment: M_COUNT_INCREMENT, decrement: M_COUNT_DECREMENT, }),
Any idea ?
Thank's