Vue State Management with Vuex

Setting up a Vuex Store:

The first step in setting up a Vuex store involves installing it through npm or yarn.

Own Vuex store can be created as soon as “state”, “mutations”, “actions” and “getters” have been defined.

For instance, the state refers to data held by your app; mutations are functions that directly manipulate the state; actions are functions that commit mutations asynchronously; getters are functions that derive other state information from the current state of store.

Examples:

Bash

                                  
                                  # Install Vuex
npm install vuex
                                  
                                

Javascript

                                  
// 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++;
    },
    decrement(state) {
      state.counter--;
    }
  },
  actions: {
    asyncIncrement(context) {
      setTimeout(() => {
        context.commit('increment');
      }, 1000);
    }
  },
  getters: {
    doubleCounter(state) {
      return state.counter * 2;
    }
  }
});

                                  
                                

In this example, we've defined a Vuex store with a counter state, increment and decrement mutations, asyncIncrement action, and doubleCounter getter.

Mutations, Actions, and Getters:

  • Mutations: Mutations on their part refer to synchronous functions used in modifying states within a Vuex shop. Such components call them via the commit method but they should always be synchronous so as to properly track changes related to conditions. Mutations receive the current state as the first argument and can also accept additional payload arguments.
  • Actions: Actions are asynchronous methods which perform side effects and make mutations. Components use the dispatch to invoke them while executing such asynchronous operations as API calls or timeouts before making mutations.
  • Getters: Getters are functions that calculate derived state based on the store’s state.The getters are similar to computed properties in Vue components and they will only re-evaluate when their dependencies have changed.Getters take in the current state as argument one, and can also receive additional getter arguments.

Vuex is a centralized data storage management system that allows keeping all the necessary information about the application’s state in one place.

It uses a unidirectional flow for data transfer which means that it has to follow strict rules concerning mutation, action, and getter used for direct modification of states asynchronously; building blocks of Vuex respectively.