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

ier*_*dna 11 vue.js vuex

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

state: {
    authed: false
    ,id: false
}
Run Code Online (Sandbox Code Playgroud)

在组件内部,我想监视authed状态的变化并向服务器发送AJAX调用.它需要在各种组件中完成.

我尝试过使用store.watch(),但无论何时发生变化idauthed发生变化.我也注意到,它不同于vm.$watch你不能指定一个属性.当我试图这样做:

store.watch('authed',function(newValue,oldValue){
  //some code
});
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误:

[vuex] store.watch only accepts a function.

任何帮助表示赞赏!

Pri*_*ome 24

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

watch: {
  'authed': function () {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)


Emi*_*íaz 11

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

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

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