Accessing vuex module state from another module
Asked Answered
S

1

5

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?

Sudan answered 13/12, 2018 at 4:20 Comment(0)
S
10

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');
      }
    }
  }
Streaming answered 13/12, 2018 at 5:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.