How to make multiple commits in vuex?

Member

by dedrick , in category: Javascript , 2 months ago

How to make multiple commits in vuex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 2 months ago

@dedrick 

To make multiple commits in Vuex, you can use the commit method inside your Vuex store actions. Here is an example of how to make multiple commits in Vuex:

  1. Define your Vuex store with some initial state, mutations, and actions:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    counter: 0
  },
  mutations: {
    increment(state) {
      state.counter++
    },
    decrement(state) {
      state.counter--
    }
  },
  actions: {
    increaseCounter({ commit }) {
      commit('increment')
      commit('increment')
    },
    decreaseCounter({ commit }) {
      commit('decrement')
      commit('decrement')
    }
  }
})

export default store


  1. Use the commit method inside your actions to make multiple commits:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// App.vue
<template>
  <div>
    <h1>{{ counter }}</h1>
    <button @click="increaseCounter">Increase</button>
    <button @click="decreaseCounter">Decrease</button>
  </div>
</template>

<script>
export default {
  computed: {
    counter() {
      return this.$store.state.counter
    }
  },
  methods: {
    increaseCounter() {
      this.$store.dispatch('increaseCounter')
    },
    decreaseCounter() {
      this.$store.dispatch('decreaseCounter')
    }
  }
}
</script>


In the above example, we have defined two actions increaseCounter and decreaseCounter that make multiple commits to the mutations increment and decrement respectively. When you click the "Increase" button, the counter will increase by 2, and when you click the "Decrease" button, the counter will decrease by 2.


This is how you can make multiple commits in Vuex by using the commit method inside your actions.