Vuex:如何等待动作完成?

时间:2020-03-26 10:03:22

标签: 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'])
},

我到达商店并调度登录操作。

商店中的操作如下:

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

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

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

2 个答案:

答案 0 :(得分:3)

您的action返回一个promise,因此您可以控制台 承诺已在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
  })
},

或者,您可以将 login 设为async函数,并将wait的{​​{1}}设为 promise 操作返回的问题已已解决

action

答案 1 :(得分:2)

您可以使用 async-await 而不是 Promise.then 。但是我的建议是不要在商店内使用Axios。在登录方法中调用Axios,然后调用商店。像这样:

System::Runtime::InteropServices::Marshal::Copy( IntPtr( ( void * ) sourcePointer), targetManagedArray, 0, dataSize ); 

然后您只需要在商店中设置对象。

相关问题