[英]How should a user be redirected to another page after successful login in Vue 3
[英]How to redirected to home after successful login with 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)
})
}
单击登录按钮后,控制台日志中的username
和jwtToken
都显示为null
。 稍后,存储中的值将更新,然后我就可以登录了。
因此,发布此消息仅几秒钟后,我在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)
})
}
这对我来说似乎有点可疑。
第一:希望您不使用vuex
来保存您的凭据/令牌。 安全提示#1 , 安全提示#2 。
我建议仅设置authenticated:true
并将其用于您的请求。
然后:查看vue router
全局防护 ,可以利用该防护来检查当前用户是否已登录。
最后:要以编程方式路由到应用程序的各个部分,可以使用router.push 。
因此,您必须存储用户在登录页面之前想要的路由,然后以编程方式在此之后push
该路由。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.