Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing vuex module state from another module

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?

like image 493
Dylan Glockler Avatar asked Jan 02 '23 12:01

Dylan Glockler


1 Answers

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');
      }
    }
  }
like image 124
Maxim Avatar answered Jan 05 '23 14:01

Maxim