How to integrate Vuex with Vue.js for state management?

Vuex is a state management library for Vue.js applications. It helps manage the state in a centralized store, making it accessible to all components.

// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    counter: 0
  },
  mutations: {
    increment(state) {
      state.counter++;
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    }
  },
  getters: {
    doubledCounter: state => state.counter * 2
  }
});

Usage in a component:

// MyComponent.vue
export default {
  computed: {
    counter() {
      return this.$store.state.counter;
    },
    doubledCounter() {
      return this.$store.getters.doubledCounter;
    }
  },
  methods: {
    increment() {
      this.$store.commit('increment');
    },
    incrementAsync() {
      this.$store.dispatch('incrementAsync');
    }
  }
};

 

Post your Answer