当 vuex store 中的特定状态发生变化时发出事件
Emit an event when a specific piece of state changes in vuex store
我有一个具有以下状态的 Vuex 商店:
state: {
authed: false,
id: false
}
在一个组件内,我想观察 authed
状态的变化,并向服务器发送一个 AJAX 调用。需要在各个组件中完成。
我尝试使用 store.watch()
,但当 id
或 authed
发生变化时会触发。我还注意到,它与 vm.$watch
的不同之处在于您不能指定 属性。当我尝试这样做时:
store.watch('authed', function(newValue, oldValue){
//some code
});
我收到这个错误:
[vuex] store.watch only accepts a function.
感谢任何帮助!
只需在组件中为 authed
状态设置一个 getter 并观察本地 getter:
watch: {
'authed': function () {
...
}
}
或者您可以使用...
let suscribe = store.subscribe((mutation, state) => {
console.log(mutation.type)
console.log(mutation.payload)
})
// call suscribe() for unsuscribe
我有一个具有以下状态的 Vuex 商店:
state: {
authed: false,
id: false
}
在一个组件内,我想观察 authed
状态的变化,并向服务器发送一个 AJAX 调用。需要在各个组件中完成。
我尝试使用 store.watch()
,但当 id
或 authed
发生变化时会触发。我还注意到,它与 vm.$watch
的不同之处在于您不能指定 属性。当我尝试这样做时:
store.watch('authed', function(newValue, oldValue){
//some code
});
我收到这个错误:
[vuex] store.watch only accepts a function.
感谢任何帮助!
只需在组件中为 authed
状态设置一个 getter 并观察本地 getter:
watch: {
'authed': function () {
...
}
}
或者您可以使用...
let suscribe = store.subscribe((mutation, state) => {
console.log(mutation.type)
console.log(mutation.payload)
})
// call suscribe() for unsuscribe