简体   繁体   English

如何将错误从 vuex 操作传播到 vue 组件?

[英]How to propagate an error from vuex action to vue component?

I have a no module store and I have an action loginUser , which logins the user by saving the authorization header in the state:我没有模块存储并且我有一个操作loginUser ,它通过在 state 中保存授权 header 来登录用户:

loginUser(context, user) {
      userService.login(user)
          .then(response => context.commit('SET_AUTHORIZATION', response.data))
          .catch(error => { throw error.response.data })
    }

The problem is that I need the error in the login component and I can't store it in the state, since I made the store to be persistent as long as the session is active.问题是我需要登录组件中的错误并且我不能将它存储在 state 中,因为只要 session 处于活动状态,我就使存储保持不变。 My submit function in the login component looks like this:我在登录组件中提交 function 如下所示:

  async onSubmit() {
        let user = {
          username: this.username,
          password: this.password,
        }
        await this.$store.dispatch('loginUser', user)
              .catch(error => {
                  if(error.response.status === 401) this.loginError = error.message
                  else console.error(error)
        })
        await this.$router.push('/').then(() => location.reload())
      }
    },

This just throws an Uncaught (in promise) .这只是抛出一个Uncaught (in promise)

You can return a Promise from your loginUser action like:您可以从loginUser操作返回Promise ,例如:

loginUser(context, user) {
  return new Promise((resolve, reject) => {
    userService.login(user)
      .then((response) => {
        context.commit('SET_AUTHORIZATION', response.data)
        resolve(response)
      })
      .catch((error) => {
        reject(error.response.data)
      })
  })
}

and then you can update your async onSubmit() method and catch that error using try..catch like:然后您可以更新您的 async onSubmit()方法并使用try..catch捕获该错误,例如:

async onSubmit() {

  try {
    let user = {
      username: this.username,
      password: this.password,
    }
    await this.$store.dispatch('loginUser', user);
    await this.$router.push('/');
    location.reload();
  } catch (error) {
    if (error.response && error.response.status === 401) 
      this.loginError = error.message
    else 
      console.error(error)
  }

},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM