Vue登录功能 [英] Vue login function

查看:38
本文介绍了Vue登录功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将通过JWT身份验证的后端连接到Vue中的登录组件.这是我的Vuex动作:

I'm trying to hook up my backend with JWT authentication to a login component in Vue. This is my Vuex action:

userLogin({commit}, payload) {
        axios.post('/users/token/obtain/', {
            email: payload.email,
            password: payload.password,
        })
            .then(response => {
                    localStorage.setItem('access', response.data.access)
                    localStorage.setItem('refresh', response.data.refresh)
                    let body = JSON.parse(atob(response.data.access.split('.')[1]))
                    commit('userLogin', {
                        userToken: response.data.access,
                        userEmail: body.email,
                        userFirstName: body.first_name,
                        userLastName: body.last_name,
                        userOrganization: body.organization
                    })
                },
                error => Promise.reject(new Error(error))
            )
    }

然后在我的登录表单上提交方法:

And the submit method on my login form:

onSubmit() {
  const formData = {
    email: this.email,
    password: this.password,
  }
  this.$store.dispatch('userLogin', {email: formData.email, password: formData.password}).then(
      success => {
        console.log(success)
        this.$router.push('/dashboard')
      },
      error => this.errorMessage = error.message
  )
}

问题在于,如果存在登录表单,则登录表单不会捕获该错误,它总是执行成功部分,并重定向到/dashboard .当我输入正确的电子邮件和密码时,它可以正常工作-状态会根据令牌中收到的信息进行更新.

The problem is that the login form doesn't catch the error if there is one, it always performs the success portion and redirects to /dashboard. It works properly when I enter a correct email and password - the state is updated with the information received in the token.

我在诺言方面做错了吗?

Am I doing something wrong with regard to promises?

推荐答案

这是我使用 async ... await :

首先将vuex动作声明为 async 函数,并使其在成功和失败情况下都返回一个值,如下所示:

first declare vuex action as an async function and make it return a value in both success and fail cases like this:

async login({ commit }, payload) {
  try {
    const response = await axios.post('url', payload);
    if (!desiredResponse) throw new Error('some message');
    // do something with response
    return true;
  } catch (e) {
    // do something else
    return false;
  }
}

在上面的代码中,任何网络错误都直接进入catch块,该错误最终在末尾返回false,并且如果响应不满足某些条件(例如"desiredResponse"),它也会引发错误并进入catch块,并且返回false.因此,我们可以在此处处理两种错误并返回false,但是如果没有错误,请尝试继续执行代码并返回true.

in the above code any network error goes directly in the catch block which returns false at the end and also if the response does not satisfy some condition i.e. "desiredResponse", it also throws an error and goes into the catch block and returns false. So we can handle both kind of errors here and return false but if there is no error, try block code continues and return true.

现在在我们的组件中,我们可以使用该异步函数的返回结果,如下所示:

now in our component we can use the returned result of that async function like this:

this.$store.dispatch('login', payload).then((res) => {
  if (res) {
    // do something
  } else {
    // do something else
  }
});

这样,我们实际上使用组件中的返回值来决定下一步要做什么.

this way we actually use the returned value in our component to decide what to do next.

当然,您可以返回其他一些值来代替true/false并根据它们决定下一步要执行的操作.

of course you can return some other values instead of true / false and decide for the next action to take based on them.

这篇关于Vue登录功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆