首页 > 解决方案 > 使用 Vue.JS 成功登录后如何重定向到主页

问题描述

我有一个登录页面。如果登录成功,我希望我的应用程序将用户重定向到主页。然后使用 API 检查凭据。我的问题是,我的 vue 页面在成功检查凭据之前重定向了用户。

在 vue.js 帮助论坛上看到类似的主题,我知道我应该发送登录请求,然后等待响应承诺解决。我觉得这就是我正在做的事情,但它显然不会在重定向之前等待响应得到解决。

这是我的 vue 页面中的代码(脚本部分)。当我单击“登录”按钮时,该onSigninClick()方法被调用:

import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'SignInLayout',
  data () {
    return {
      username: null,
      password: null
    }
  },
  computed: {
    ...mapGetters('TemplaterAuth', [
      'logged',
      'getUsername',
      'getJwtToken'
    ])
  },
  methods: {
    ...mapActions('TemplaterAuth', [
      'authenticate'
    ]),
    onSigninClick () {
      let creds = {
        username: this.username,
        password: this.password
      }
      this.authenticate(creds).then(response => {
        console.log(this.getUsername)
        console.log(this.getJwtToken)
        console.log('logged:')
        console.log(this.logged)
        this.$router.push('/')
      })
    }
  }
}

和我的authenticate()方法:

export function authenticate (context, creds) {
  let requestConfig = {
    headers: {
      'Content-Type': 'application/json'
    }
  }
  Vue.http.post(
    url + apiPaths.auth,
    creds,
    requestConfig
  ).then(response => {
    return response.json()
  }).then(data => {
    context.commit('setUsername', creds.username)
    context.commit('setJwtToken', data.token)
  }).catch(error => {
    console.log('error:')
    console.log(error)
  })
}

当我单击一次登录按钮时,我的控制台日志null同时显示usernamejwtToken. 片刻之后,这些值在商店中更新,然后我就可以登录了。

标签: javascriptvue.jsvuejs2vuex

解决方案


因此,在发布此消息几秒钟后,我在 Vue 论坛上得到了答案:我需要我的方法return的承诺。authenticate所以新代码是:

export function authenticate (context, creds) {
  let requestConfig = {
    headers: {
      'Content-Type': 'application/json'
    }
  }
  return Vue.http.post(
    url + apiPaths.auth,
    creds,
    requestConfig
  ).then(response => {
    return response.json()
  }).then(data => {
    context.commit('setUsername', creds.username)
    context.commit('setJwtToken', data.token)
  }).catch(error => {
    console.log('error:')
    console.log(error)
  })
}

资源


推荐阅读