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

时间:2018-06-19 15:45:49

标签: vue.js vuex

我了解了store.watch(),但是找不到有效的示例...

  

Vuex手表   watch(fn:函数,回调:函数,选项?:对象):函数   被动地观察fn的返回值,并在值更改时调用回调。 fn将存储状态作为第一个参数,将getters作为第二个参数。接受一个可选的options对象,该对象采用与Vue的vm。$ watch方法相同的选项。   要停止观看,请调用返回的取消观看功能。

我有一个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)
  })
},

我正在从我的登录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)
      })

但是我收到Vuex错误

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

我正在传递一个函数,不是吗?

感谢您的反馈

1 个答案:

答案 0 :(得分:1)

watch的第一个参数是一个将状态作为第一个参数并将getters作为第二个参数的函数。因此,像这样访问吸气剂,返回值就是被监视的那个。

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