How to use mutations and actions in vuex?

Member

by jerad , in category: Javascript , 6 months ago

How to use mutations and actions in vuex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , 6 months ago

@jerad 

In Vuex, mutations are used to modify the state of the store, while actions are used to perform asynchronous tasks or complex logic before committing a mutation. Here is how you can use mutations and actions in Vuex:

  1. Define a state object in your Vuex store file:
 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
32
33
34
35
36
// 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: {
    incrementAsync(context) {
      setTimeout(() => {
        context.commit('increment');
      }, 1000);
    },
    decrementAsync({ commit }) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          commit('decrement');
          resolve();
        }, 1000);
      });
    }
  }
});

export default store;


  1. Use computed properties or mapState to access the state in your component:
 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
// MyComponent.vue
<template>
  <div>
    <p>Counter: {{ counter }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
  </div>
</template>

<script>
import { mapState } from 'vuex';

export default {
  computed: {
    ...mapState(['counter'])
  },
  methods: {
    increment() {
      this.$store.commit('increment');
    },
    decrement() {
      this.$store.dispatch('decrementAsync').then(() => {
        console.log('Counter decremented');
      });
    }
  }
}
</script>


In this example, the state object has a counter property. The increment and decrement mutations modify this property. The incrementAsync action commits the increment mutation after a delay. The decrementAsync action commits the decrement mutation after a delay, and returns a promise that can be used to perform additional logic after the mutation. In the component, the counter is accessed using computed properties or the mapState helper. The increment method commits the increment mutation, and the decrement method dispatches the decrementAsync action and performs additional logic using the returned promise.