SoFunction
Updated on 2025-04-04

Interpretation of the relationship between state, getters, mutations, actions in vuex

1. How to use state

<body>
  <!-- 
    Want to get itstateData in
    {{$.property}}
    I thought this expression was very long,So we can passcomputedGo and get it
    {
      computed: {
        property名 () {
          return this.$.property
        }
      }
    }
    {{property名}}
   -->
  <div >
    {{$}}
    <br>
    {{msg}}
    <br>
    {{m}}
  </div>
  <script src="./"></script>
  <script src="./"></script>
  <script>
    const store = new ({
      // state is an object that contains the state (data) in each component. state is a global data that can be obtained anywhere      state: { 
        msg: 'Hello Vuex'
      }
    })
 
    const app = new Vue({
      el: "#app",
      store,
      data: {
        m: 'Own data'
      },
      computed: {
        msg () {
          return this.$
        }
      }
    })
  </script>
</body>

2. How to use getters

<body>
  <div >
    <!-- {{$}} -->
    {{boys}}
    <!-- {{$}} -->
    <br>
    {{$(53)}}
  </div>
  <!-- 
    {
      state: {
      },
      getters: {
        gettername (state, getters) {
          // Because our getter data is obtained from the state          // We can also get the corresponding data from other getters        },
        gettername (state) {
          // Return a function          return (parameter) => {
            // Return data in the function, we can add formal parameters to the function            return data 
          }
        }
      }
    }
    When using,直接返回data的getterThen we can
    {{$}}
    Return the function's,We can
    {{$(parameter)}}
    No matter whatgetterstillstate,When using,We can all directly
    $/state.属性name
    Because it's too long,So it can be written incomputed
    computed: {
      属性name () {
        return this.$/state.属性name
      }
    }
   -->
  <script src="./"></script>
  <script src="./"></script>
  <script>
    const store = new ({
      state: {
        stus: [
          {
            name: 'Zhang San21',
            age: 18,
            sex: 'female'
          }, {
            name: 'Zhang San42',
            age: 14,
            sex: 'female'
          }, {
            name: 'Zhang San42',
            age: 54,
            sex: 'female'
          }, {
            name: 'Zhang San2',
            age: 34,
            sex: 'female'
          }, {
            name: 'Zhang San4',
            age: 13,
            sex: 'male'
          }, {
            name: 'Zhang San52',
            age: 53,
            sex: 'male'
          }
        ]
      },
      getters: {
        boys (state) {
          return (stu =>  === 'male')
        },
        boysLength (state, getters) {
          return 
        },
        ageStu (state) {
          // return (stu =>  > 20)
          return (age) => {
            return (stu =>  > age)
          }
        },
        /* ageStu: state => age => (stu =>  > age) */
      }
    })
 
    const app = new Vue({
      el: '#app',
      store,
      computed: {
        boys () {
          return this.$
        }
      }
    })
  
  </script>
</body>

III. Usage of mutation

<body>
  <!-- 
    ChangevuexmiddlestateThe only way to submitmutation,mutationThe codes are synchronized
    mutationSimilar to custom events
    Want to changestatemiddle的值,Then we just need tomutationsmiddle添加对应的mutationfunction
    这个function只需要管改变操作Just
    然后在组件middle的事件function里提交对应mutationJust
    {
      mutations: {
        mutationfunction (state, payload) {
          // Because mutation changes the value in state, there is a state in our parameter that allows us to quickly change the corresponding value          // Payload receives data passed from commit        }
      }
    }
    组件functionmiddle提交mutation
    {
      methods: {
        function () {
          this.$('mutation name', data)
        }
      }
    }
    Sometimes objects do not support responsiveness.,So we should use
    this.$set(Object, 'property', 'Attribute Value')
    this.$delete(Object, 'property')
    
    ()
    ()
  -->
  <div >
    <button @click="changeMsg">Button</button>
    <br>
    {{msg}}
    <br>
    <ul>
      <li v-for="value in obj">{{value}}</li>
    </ul>
  </div>
  <script src="./"></script>
  <script src="./"></script>
  <script>
  
 
    const store = new ({
      state: {
        msg: 'information'
      },
      mutations: {
        changeMsg (state, payload) {
          // Just change the state here           = 
          
        },
        [mutation_types.MUTATION1] () {
 
        }
      }
    })
 
    const app = new Vue({
      el: '#app',
      store,
      data: {
        obj: {
          a: 1
        }
      },
      computed: {
        msg () {
          return this.$
        }
      },
      methods: {
        changeMsg () {
          this.$('changeMsg', {msg: 'Values ​​in Component', a: 2})
        }
      }
    })
  </script>
</body>

4. Usage of action

<body>
  <div >
    {{users}}
  </div>
  <!-- 
    actionUsage andmutationsimilar
    actionAsynchronous operations are involved
    actionNeed to be distributed
    this.$('action name', data)
    actions: {
      actionname (context, payload) {
        Make asynchronous requests
        contextis a andstoreExactly the same object,payloadthat isdispatch时传递过来的data
        ('mutation')
      },
      actionname ({commit}, payload) {
        commit('mutation')
      },
      actionname ({commit, state}, payload) {
        // The purpose of getting state here is to get the data in state, but it cannot be modified      }
    }
   -->
  <script src="./"></script>
  <script src="./"></script>
  <script src="./"></script>
  <script>
    const store = new ({
      state: {
        users: []
      },
      mutations: {
        setUsers (state, users) {
           = users
        }
      },
      actions: {
        getUsers (context, page) {
          ('http://localhost:3000/user/listpage?page=' + page).then(res => {
            // ()
            // Submit mutation in the request result of the action            // Because context and $store are consistent, we can directly call the commit method of context to submit mutation            ('setUsers', )
          })
        }
      }
    })
 
    const app = new Vue({
      el: '#app',
      store,
      computed: {
        users () {
          return this.$
        }
      },
      created () {
        // Distribute the action here        this.$('getUsers', 2)
      }
    })
  
  </script>
</body>

5. Summary

<script>
    /*
       state
         Save component data
      
         If you want to use msg data in your component, the easiest
         direct
           {{$}} in the template
           This.$ in the function
 
           If you want to look good,
           computed: {
             msg () {
               return this.$ // You can use msg directly elsewhere
             }
           }
    
       When used in a component, the getter is similar to the state method. You need to change the state to getters
         Want to use reverseMsg
         direct
           {{$}} in the template
           This.$ in the function
        
         If you want to look good,
         computed: {
           reverseMsg () {
             return this.$
           }
         }
      
       mutation
         Mutation is a function, its function is to modify the state, and it can only be modified in this way
        
         If we want to modify a certain data in the component, we can directly submit the corresponding mutation
         this.$('setMsg', 'Related Data')
 
         Because mutation needs to change state, there are parameters state and payload in mutation
 
       Action
         Usage is similar to mutation
        
         1. Commit is required to pass a value to a mutation
           This is an accepted operation
           {
             mutations: {
               mutation function (state, payload) {
                 // Because mutation changes the value in state, there is a state in our parameter that allows us to quickly change the corresponding value
                 // Payload receives data passed from commit
               }
             }
           }
 
           Submitting mutation in component functions is to pass the value to the mutation
           {
             methods: {
               Function () {
                 this.$('mutation function', data)
               }
             }
           }
 
         2. Transferring value to action requires dispatch
         this.$('action name', data)
        
         Because mutation modifies state synchronously, there is state in the parameters
         However, the action is to obtain data asynchronously. If the data is retrieved, you want to modify it to the state. Therefore, you must submit a mutation to modify the state in the action function. Therefore, there is a parameter context in the action function, and this context is a store
         If you want to submit, then ('function name in mutation', value passed)
        
        
     */  
    
    const store = new ({
      state: {
        msg: 'data'
      },
      getters: {
        reveseMsg () {
          return ('').revese().join('')
        }
      },
      mutations: {
        setMsg (state, payload) {
           = payload
        } 
      }
    })
     <!-- 
    VuexCommonly used
      state mutations actions
    If we want to render some data in the page,Then we can put the data instatemiddle state
    If we want to operate page elements to modify data,那么我们就要在事件处理函数middlethis.$('mutation')  submitmutation letmutationGo to modify
    If we want to operate the page element to get new data,那么我们就要在事件处理函数middlethis.$('action')  Then when the requested data is successful,letactiongocommit('mutation')  ThenmutationModify data
    actionmiddle的代码只涉及到,Request data submitmutation
    mutation Only involve modificationsstate
    组件middle设置到submitmutationOr distributeaction
   -->
  </script>

The above is personal experience. I hope you can give you a reference and I hope you can support me more.