SoFunction
Updated on 2025-04-04

vuex mutations Synchronous operation method details

Function: Modify the state in vuex, only through mutations

  • You need to submit a synchronization method through commit (1. Only submit the method, refer to Example 1; 2. Carry parameters for submission, refer to Example 2)
  • The first default parameter in the synchronization method is state, which can be obtained by taking the data already defined in the state.
// Define some initial data in state to give examplesstate: {
  // Define a number  count: 0,
  // Define an object  coderyg: {
    name: 'coderyg',
    age: 25,
    height: 1.93
  },
  // Define a string  info: 'swk'
}

Example 1: Modify count (only submit method)

// 
<p>{{ $ }}</p> //The count at this time is 0<button @click="addCount">+</button>
<button @click="subCount">-</button>
// Submit SynchronizationaddCount() {
  this.$('increment');
},
subCount() {
  this.$('decrement');
}
// 
// Receive synchronizationincrement(state) {
   ++;
},
decrement(state) {
   --;
}

Example 2.1: Submit with parameters

// 
<p>{{ $ }}</p> //The count at this time is 0<button @click="changeNum(+5)">+5</button>
<button @click="changeNum(-5)">-5</button>
// Submit Synchronization--directly submit parameters, num is a numberchangeNum(num) {
  this.$('addNum', num);
}
// 
// Receive synchronizationaddNum(state, num) {
   += num;
}

Example 2.2: Methods for carrying parameter object

// 
<p>{{ $ }}</p> //The count at this time is 0<button @click="changeNum(+5)">+5</button>
<button @click="changeNum(-5)">-5</button>
// Submission synchronization - object submission will be submitted with the entire payload, by obtaining the submitted past informationchangeNum(num) {
  this.$(Start from here{
    type: 'addNum',
    num
  }At the end of this ispayload);
}
// 
// Receive synchronizationaddNum(state, payload) {
   += ;
}

This is the end of this article about the detailed explanation of the synchronization operation method of vuex mutations. For more detailed explanation of the synchronization operation method of vuex mutations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!