【问题标题】:Emit an event when a specific piece of state changes in vuex store当 vuex 存储中的特定状态发生变化时发出事件
【发布时间】:2017-02-11 13:56:08
【问题描述】:

我有一个具有以下状态的 Vuex 商店:

state: {
    authed: false,
    id: false
}

在组件内部,我想观察authed 状态的变化并向服务器发送AJAX 调用。它需要在各个组件中完成。

我尝试使用store.watch(),但是当idauthed 更改时会触发。我还注意到,它与vm.$watch 的不同之处在于您不能指定属性。当我尝试这样做时:

store.watch('authed', function(newValue, oldValue){
  //some code
});

我收到了这个错误:

[vuex] store.watch only accepts a function.

感谢任何帮助!

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    只需在您的组件中为 authed 状态设置一个 getter 并观察该本地 getter:

    watch: {
      'authed': function () {
        ...
      }
    }
    

    【讨论】:

      【解决方案2】:

      或者你可以使用...

      let suscribe = store.subscribe((mutation, state) => {
        console.log(mutation.type)
        console.log(mutation.payload)
      })
      // call suscribe() for unsuscribe
      

      https://vuex.vuejs.org/api/#subscribe

      【讨论】:

        猜你喜欢
        • 2019-10-05
        • 2020-10-21
        • 1970-01-01
        • 1970-01-01
        • 2018-03-07
        • 1970-01-01
        • 2021-07-05
        • 2017-10-18
        • 2019-10-11
        相关资源
        最近更新 更多