This page looks best with JavaScript enabled

Setup Modular Vuex

 ·   ·  ☕ 2 min read

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// 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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
//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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// 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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things