我读过 store.watch() ,但找不到有效的例子......
Vuex watch watch(fn: Function, callback: Function, options?: Object): Function 反应式地观察fn的返回值,当值发生变化时调用回调。fn 接收 store 的 state 作为第一个参数,getter 作为第二个参数。接受一个可选的选项对象,该对象采用与 Vue 的 vm.$watch 方法相同的选项。要停止观看,请调用返回的 unwatch 函数。
我有一个用户使用 Firebase 登录的 Vuex 操作
signUserIn ({commit}, payload) {
commit(types.SET_LOADING, true)
commit(types.CLEAR_ERROR)
firebase.auth().signInWithEmailAndPassword(payload.email, payload.password)
.then((user) => {
commit(types.SET_LOADING, false)
const newUser = { id: user.uid, name: user.displayName, email: user.email, photoUrl: user.photoURL }
commit(types.SET_USER, newUser)
})
.catch((error) => {
commit(types.SET_LOADING, false)
commit(types.SET_ERROR, error)
})
},
Run Code Online (Sandbox Code Playgroud)
我正在从我的 Signin vue 组件分派此操作
在我的业务案例中,由于用户尚未注册,因此登录失败,因此在商店中引发并提交了错误,但在我的组件中,我不会在分派后立即获取错误,因此我将商店中的加载值设置为 true /false 并且我需要观察它的变化...所以我尝试使用 store.watch()
onSignIn 方法(验证后)
this.$store.dispatch('signUserIn', { email: this.email, password: this.password })
console.log('loading...: ', this.$store.getters.loading)
this.$store.watch(this.$store.getters.loading, () => {
console.log('loaded')
console.log('onSIgnin error', this.error.code)
})
Run Code Online (Sandbox Code Playgroud)
但我收到 Vuex 错误
Error: [vuex] store.watch only accepts a function
Run Code Online (Sandbox Code Playgroud)
我正在传递一个函数,不是吗?
感谢反馈
watch 的第一个参数是一个函数,它接收状态作为第一个参数,接收器作为第二个参数。所以像这样访问getter,返回值就是被监视的那个。
this.$store.watch((state, getters) => getters.loading, () => {
console.log('loaded')
console.log('onSIgnin error', this.error.code)
})
Run Code Online (Sandbox Code Playgroud)