Home > Web Front-end > JS Tutorial > Detailed explanation of Mutations modification status operation in Vuex

Detailed explanation of Mutations modification status operation in Vuex

coldplay.xixi
Release: 2020-07-29 17:25:52
forward
2350 people have browsed it

Detailed explanation of Mutations modification status operation in Vuex

The previous article was about reading state, and this article is about modifying state. That is, how to operate Mutations.

1. $store.commit( )

Vuex provides the commit method to modify the status

1.store.js file

const mutations={
  add(state){
    state.count++
  },
  reduce(state){
    state.count--
  }
}
Copy after login

2. Modification method on button

2. Pass value

The simplest operation to modify the state. In actual projects, we often need to pass values ​​when modifying the state. For example, in the above example, we only add 1 each time, but now we need to add the values ​​passed. In fact, we only need to add another parameter to Mutations and pass it when committing. Let’s look at the specific code:

1.store.js

const mutations={
  add(state,n){
    state.count+=n
  },
  reduce(state){
    state.count--
  }
}
Copy after login

2. Modify the parameters passed by the commit() method of the button. We pass 10, which means adding 10 each time.

3. Template acquisition method of Mutations

We don’t like to see it in actual development either When a method like $store.commit() appears, we hope to call it the same way as the method in the template.

For example: @click="reduce" is the same as not referencing the vuex plug-in.

1. Use import to introduce our mapMutations in the template count.vue:

import { mapState,mapMutations } from 'vuex'

2 .Add the methods attribute in the

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template