首页 文章

Vue.js Vuex如何正确使用store.watch()方法?

提问于
浏览
1

我读到了关于store.watch()的内容,但找不到有效的例子......

Vuex Watch (fn:功能,回调:功能,选项?:对象):功能反应查看fn的返回值,并在值更改时调用回调 . fn接收商店的状态作为第一个参数,getter作为第二个参数 . 接受一个可选的选项对象,该对象采用与Vue的vm . $ watch方法相同的选项 . 要停止观看,请调用返回的unwatch功能 .

我有一个Vuex操作,用户登录Firebase

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)
  })
},

我从我的Signin vue组件发送此操作

在我的商业案例中,登录失败,因为用户尚未注册,因此提出错误并在商店中提交,但在我的组件中,我不会在发送后立即获取错误,因此我在商店中将加载值设置为true / false我需要看它改变...所以我尝试使用store.watch()

onSignIn method ( after validation)

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)
      })

但是我得到了Vuex错误

Error: [vuex] store.watch only accepts a function

我正在传递一个功能,不是吗?

谢谢你的反馈

1 回答

  • 2

    watch的第一个参数是一个函数,它接收状态作为第一个参数,getter作为第二个参数 . 因此,像这样访问getter,返回值是正在观看的那个 .

    this.$store.watch((state, getters) => getters.loading, () => {
            console.log('loaded')
            console.log('onSIgnin error', this.error.code)
          })
    

相关问题