Search code examples
javascriptvue.jsvuexstore

Splitting Vuex module into multiple files in the same namespace


I am trying to split my Vuex module into chunks. In addition to creating multiple namespaced modules (namespaced: true), I want to extend the global module that became extremely long. It seems that in some cases, it is preferred to keep some of my actions/mutations in the global module, as they communicate with each other and are too coupled, but using { root: true } option each time I need to execute an action or mutation is not feeling good enough in my opinion. So, in my case, not setting namespaced to true sounds like the perfect solution.

But...

First of all - it seems like not-namespaced modules can't hold their own state. Moreover - when they try to use state delivered to the actions/mutations, they fail since they can't communicate with the root state directly (just with rootState param, which is not what i was expecting).

One more possible solution I could think of is to init my Vuex store like this:

export default new Vuex.Store({
  namespaced: true,
  state: {},
  getters: {},
  mutations: {},
  actions: {
    ...actionsFromFile1,
    ...actionsFromFile2
  }
});

But this solution yet doesn't seem the best. Is there any other solution I'm missing?


Solution

  • You should keep your actions and mutations in your modules.

    As you mentioned you can use root to dispatch actions of other modules. Why you should use this, is easy. Visibility - If you need to dispatch an action from another store keep it in the module where you expect it, splitting code into your global store and modules will make it hard to track where things come from.

    Also your global store will grow and you will have a hard time finding what you want to later.

    simple example:

    // message.js
    
    const actions = {
      add({ dispatch }, message) {
        dispatch("chat/initializeChat", {}, { root: true });
    
        // add message or something
      },
    };