vue.js 如何查看全局存储的对象的状态变化

idfiyjo8  于 7个月前  发布在  Vue.js
关注(0)|答案(1)|浏览(78)

我正在使用vue3options api
我正在学习如何使用global-store我参考了vue的官方网站,并在论坛上阅读了一些帖子.如以下链接中的代码所示:
https://stackblitz.com/edit/vue-xltavx?file=src%2FApp.vue,src%2Fcomponents%2FHelloWorld.vue,src%2Fstore%2FStoreMajoreEnableState.vue
我将StoreMajorEnableState.vue创建为可组合的,并且我希望watchstoreMajorEnableState状态的更改。为了解决这个问题,在app组件中,我添加了以下内容

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

字符串

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


但是他们都没有解决这个问题,我想知道我怎么能看到storeMajorEnableState状态的变化。

myss37ts

myss37ts1#

对于全局状态管理,最好使用vuex。它的设置与上面的设置相同。下面是如何设置简单vuex存储的示例。

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)
    }
  }
})

字符串
现在我不知道你为什么要监视全局状态,或者你有什么具体的用例,但是如果你在任何组件中调用vuex getter(最好是在计算属性中),那么每当你的全局状态count被更新时,getter就会被再次调用。希望这能解决你的问题。

相关问题