Vuex

Vuex

Vuex has been used as state management solution.
Every feature is organized in a folder containing three fundamental atomic part of Vuex flow as two separate file: mutation and actionCreator for better structure.
For asynchronous state operations, well opinionated three actions model has been used. And the actions consist of [state]\_BEGIN,[state]\_SUCCESS,[state]\_FAILED.

Locate the Vuex folder in src/vuex

Mutation

mutation.js file contains of all mutation types and payload required for any apps. Below is an example of authentication.


export default {
  loginBegin(state) {
    state.login = true;
  },
  loginSuccess(state, data) {
    state.loading = false;
    state.login = data;
  },

  loginErr(state, err) {
    state.loading = false;
    state.error = err;
  },

  logoutBegin(state) {
    state.loading = true;
  },

  logoutSuccess(state, data) {
    state.loading = false;
    state.login = data;
  },

  logoutErr(state, err) {
    state.loading = false;
    state.error = err;
  },
};
                                                    
ActionCreator

Create all the mutations declared in mutation.js file and pass the data in actionCreator.js file


import mutations from './mutations';
import Cookies from 'js-cookie';

const state = () => ({
  login: Cookies.get('logedIn'),
  loading: false,
  error: null,
});

const actions = {
  async login({ commit }) {
    try {
      commit('loginBegin');
      Cookies.set('logedIn', true);
      return commit('loginSuccess', true);
    } catch (err) {
      commit('loginErr', err);
    }
  },
  async logOut({ commit }) {
    try {
      commit('logoutBegin');
      Cookies.remove('logedIn');
      commit('logoutSuccess', null);
    } catch (err) {
      commit('logoutErr', err);
    }
  },
};

export default {
  namespaced: false,
  state,
  actions,
  mutations,
};
                                                    
store.js

Finally locate the store.js file from src/vuex/store.js. Import the all states, actions and mutations from actionCreator.js file.


import { createStore } from 'vuex';
import themeLayout from './modules/themeLayout/actionCreator';
import gallery from './modules/gallery';

export default createStore({
  modules: {
    themeLayout,
    gallery,
  },
});