当vuex存储中的特定状态更改时发出事件

时间:2016-10-03 15:03:52

标签: vue.js vuex

我有一个具有以下状态的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.

感谢任何帮助!

2 个答案:

答案 0 :(得分:23)

只需在组件中为authed状态设置一个getter,然后观察当地的getter:

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

答案 1 :(得分:9)

或者你可以使用......

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

https://vuex.vuejs.org/en/api.html