0

I know a similar question has been asked here but mine is a little bit different, the state I want to watch is inside some nested modules. on the link above they suggested I can watch the state like this:

watch: {
  '$store.state.drawer': function() {
    console.log(this.$store.state.drawer)
  }
}

But my state is in nested modules as I mentioned, something like store/moduleOne/moduleTwo/moduleThree They suggested to do this:

$store.state.moduleOne.moduleTwo.moduleThree.something

But I tried it and many more variations and it didn't work! I asked on the original post and no answers!

So my question is how can I watch a state, let's call it price and let's say it's in store/moduleOne/moduleTwo/moduleThree and then log its value in my component whenever it changes using (using map functionalities is no problem and is preferred)

E_net4
  • 27,810
  • 13
  • 101
  • 139
seyet
  • 1,080
  • 4
  • 23
  • 42

1 Answers1

0

Assuming nested modules declared in Vuex 4 like this:

import { createStore } from 'vuex'

export default createStore({
  modules: {
    moduleOne: {
      namespaced: true,
      modules: {
        moduleTwo: {
          namespaced: true,
          modules: {
            moduleThree: {
              namespaced: true,
              state: () => ({
                price: 0,
              }),
              mutations: {
                SET_PRICE(state, price) {
                  state.price = price
                },
              },
            },
          },
        },
      },
    },
  },
})

...the watcher on the price state in moduleThree would be:

export default {
  watch: {
    '$store.state.moduleOne.moduleTwo.moduleThree.price'(price) {
      console.log({ price })
    }
  }
}

demo

tony19
  • 125,647
  • 18
  • 229
  • 307