Accessing vuex module state from another module

Dylan Glockler picture Dylan Glockler · Dec 13, 2018 · Viewed 7.5k times · Source

I'm learning vuex and making some headway but I'm stuck on something. I have a vue component with a store containing a number of modules. I have locations with have equipment. User selects a location and I store that in in my vuex state in the location module.

I'm trying to access the location from the equipment module to load only equipment for the chosen location.

The documentation says this should work:

actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
  if ((state.count + rootState.count) % 2 === 1) {
    commit('increment')
  }
}

When I try this in my module:

GET_EQUIPMENTS : async (context,payload, rootState) => {
  alert(JSON.stringify(rootState.location, null, 4));
}

I get error rootState is not defined.

If I alert context I can see rootGetters

{
  "getters": {},
  "state": {
    "equipments": [],
    "equipment": null
  },
  "rootGetters": {
    "locations/LOCATIONS":[
    {
       "id": 1,
       "name": "West Pico",
    }
  }
}

But I can't figure out how to access locations/LOCATIONS, I can get to rootGetters by accessing context.rootGetters.

Any advice?

Answer

Maxim picture Maxim · Dec 13, 2018

Based on https://vuex.vuejs.org/guide/modules.html

You should wrap state, commit, rootState in {..} for actions:

actions: {
    incrementIfOddOnRootSum({ state, commit, rootState }, yourParam) {
      if ((state.count + rootState.count + yourParam) % 2 === 1) {
        commit('increment');
      }
    }
  }