Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs : mapMutations

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

like image 240
Nicolas B Avatar asked Jan 05 '23 03:01

Nicolas B


1 Answers

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

like image 168
gtamborero Avatar answered Jan 13 '23 10:01

gtamborero