How to access store state from a different store module in vuex?

Member

by rollin , in category: Javascript , 5 months ago

How to access store state from a different store module in vuex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 5 months ago

@rollin 

To access store state from a different store module in Vuex, you can use the rootState parameter in your getters, actions, or mutations.


For example, if you have two store modules named moduleA and moduleB, and you want to access the state from moduleA in moduleB, you can do the following:


In moduleB, you can access the state from moduleA by using rootState.moduleA:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// moduleB.js
const moduleB = {
  getters: {
    getStateFromModuleA: (state, getters, rootState) => {
      return rootState.moduleA.someState;
    }
  },
  actions: {
    actionInModuleB({ state, getters, commit, rootState }) {
      console.log(rootState.moduleA.someState);
    }
  },
  mutations: {
    mutationInModuleB(state, payload, rootState) {
      console.log(rootState.moduleA.someState);
    }
  }
};


This way, you can access the state from moduleA in moduleB using rootState.moduleA.someState.