Setup Modular Vuex

Vuex is my preferred way to manage state within Vue. Vuex is better structured using modules to make your code more readable and maintainable.

See why you should use Vuex in Vue.

Create a Vue app as you will always do using vue create myApp. Do a cd myApp && vue add vuex if you have not selected Vuex at the very beginning.

Create a store folder in the src folder of the Vue project. This will be the root of all Vuex. Create an index file to initiate store.

// store/index.js
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  namespaced: true,
  name: "global",
  modules: {
    // all modules here
  }
});

Now start adding modules. Create a file called user.js and another file called account.js in the store folder. These files can have the basic structure of a store -

//store/user.js

export default {
  namespaced: true,
  name: "users",
  state: {
      users: []
  },
  mutations: {
    setUsers(state, users)   {
        state.users =  users;
    }
  }

Include the modules within the main index store file.

// store/index.js
import Vue from "vue";
import Vuex from "vuex";

import user from "./user";
import account from "./account";

Vue.use(Vuex);

export default new Vuex.Store({
  namespaced: true,
  name: "global",
  modules: {
    user,
    account
  }
});

You can refer modules of Vuex as easily in any Vue view or component.

You should consider adding modules for any project to retain your sanity. Although a single file can get the job done, the trauma of maintaining such code will be too great for mere words.

Last updated:
Categories: Vue
Tags: VueJS
comments powered by Disqus