Vuex:如何等待动作完成?

Aym*_*rig 9 vue.js vuex

我想实现一个登录方法。我的代码是:

login() {
  let user = {
    email: this.email,
    password: this.password
  };

  this.$store.dispatch('auth/login', user)
  console.log(this.$store.getters['auth/getAuthError'])
},
Run Code Online (Sandbox Code Playgroud)

我到达商店并发送登录操作的地方。

商店中的操作如下所示:

login(vuexContext, user) {
        return axios.post('http://localhost:8000/api/user/login', user)
        .then(res => {
            vuexContext.commit('setToken', res.data.token)
            vuexContext.commit('setUser', res.data, {root: true})
            localStorage.setItem('token', res.data.token)
            Cookie.set('token', res.data.token )
            this.$router.push('/')
        }).catch(err => {
            vuexContext.commit('setAuthError', err.response.data)
        })
    },
Run Code Online (Sandbox Code Playgroud)

在 catch 块中,如果发生错误,我会更新状态并将authError属性设置为我得到的错误。

我的问题是,在登录方法中,该console.log语句在动作实际完成之前执行,因此authError属性是尚未设置的状态。如何解决这个问题?

Shi*_*ngh 8

action正在返回apromise以便您可以在块中解决承诺后进行控制台then()

login() {
  let user = {
    email: this.email,
    password: this.password
  };

  this.$store.dispatch('auth/login', user).then(() => {
   console.log(this.$store.getters['auth/getAuthError'])
   // this.$router.push('/') // Also, its better to invoke router's method from a component than in a store file, anyway reference of a component may not be defined in the store file till you explicity pass it
  })
},
Run Code Online (Sandbox Code Playgroud)

或者,您可以使login成为一个async函数wait,并且action直到 action 返回的承诺已得到解决

async login() {
  let user = {
    email: this.email,
    password: this.password
  };

  await this.$store.dispatch('auth/login', user)
  console.log(this.$store.getters['auth/getAuthError'])
},
Run Code Online (Sandbox Code Playgroud)