Search code examples
vue.jsvuejs2vuejs3vue-component

How to watch change in the state of an object globally stored


i am using vue3 with options api

i am learning how to use global-store i referred to the offical website of vue, and read some posts in forums. as shown in the code in the followin link:

https://stackblitz.com/edit/vue-xltavx?file=src%2FApp.vue,src%2Fcomponents%2FHelloWorld.vue,src%2Fstore%2FStoreMajoreEnableState.vue

i create StoreMajorEnableState.vue as composable, and i want to watch the change in the state of storeMajorEnableState. to solve this issue, in the app component, i added the following

 watch: {
    'storeMajorEnableState_.state'(newVal, oldVal) {
        console.log('watch storeMajorEnableState_.newVal:', newVal)
        console.log('watch storeMajorEnableState_.oldVal:', oldVal)
    },
},

and

watch: {
    'storeMajorEnableState_.getters.getMajorEnableState()'(newVal, oldVal) {
        console.log('watch storeMajorEnableState_.newVal:', newVal)
    console.log('watch storeMajorEnableState_.oldVal:', oldVal)
    },
},

but neither of them solve the problem, i would like to know how can i watch the changes occure to the state of storeMajorEnableState


Solution

  • For global state management, it is preferred to use vuex. It's setup is the same as you did above. Here's an example of how to setup a simple vuex store.

    import { createStore } from 'vuex'
    
    const store = createStore({
      state: {
        count: 0
      },
      getters: {
        getCount(state) {
          return state.count;
        }
      },
      mutations: {
        setCount(state, payload) {
          state.count = payload;
        }
      }
      actions: {
        updateCount({ commit }, payload) {
          commit("setCount", payload)
        }
      }
    })

    Now I don't know why you want to watch a global state or what specific use-case you have for that, but if you call a vuex getter inside any of your components (preferably inside a computed property), then everytime your global state count is updated, the getter will be called again with the updated value. Hopefully this solves your problem.