使用Vue.JS成功登录后如何重定向到首页

时间:2018-08-17 14:48:46

标签: javascript vue.js vuejs2 vuex

我有一个登录页面。如果登录成功,我希望我的应用程序将用户重定向到首页。然后使用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)
  })
}

单击登录按钮后,控制台日志同时显示nullusername的{​​{1}}。片刻之后,这些值将在商店中更新,然后我就可以登录。

2 个答案:

答案 0 :(得分:0)

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

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

Source

答案 1 :(得分:0)

这对我来说似乎有点可疑。

首先:我希望您不使用vuex来保存凭据/令牌。 Security tip #1Security tip #2

我建议仅设置authenticated:true并将其用于您的请求。

然后: 查看vue router中的global guards,可以利用它来检查当前用户是否已登录。

最后: 要以编程方式路由到应用的各个部分,可以使用router.push

因此,您必须在登录页面之前存储用户想要的路由,然后以编程方式push之后存储该路由。

相关问题