Search code examples
vue.jsvuex

How to access state in the other module's state (vuex)?


I have two modules.

module1.js

export default {
  state: () => ({
    array: [
      {
        property: value
      }
    ]
  })
}

module2.js

export default {
  state: () => ({
    array: [
      {
        property: structuredClone(this.$store.state.module1.array[0])
      }
    ]
  })
}

I want to access a state from one module in the state in other module. How to do that?

Tried to use context in state (of course didn't work). My code generates an error ($store isn't defined)


Solution

  • I don't think you can do that, but you can use a getter because it gives you access to the root state.

    // module 1
    export default {
      state: {
        array: [
          {
            property: value
          }
        ]
      }
    }
    
    // module 2
    export default {
      getters: {
        myGetter(state, getters, rootState) {
          console.log(rootState.module1.array[0]);
        }
      }
    }