javascript - 使用 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
同时显示username
和jwtToken
. 片刻之后,这些值在商店中更新,然后我就可以登录了。
解决方案
因此,在发布此消息几秒钟后,我在 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)
})
}
推荐阅读
- flutter - heightFactor 和 widthFactor 是如何工作的?
- php - 如何覆盖 woocommerce 自定义面板文件(包含在文件夹中)
- java - 如何在应用程序上下文之前评估 spring ApplicationArguments?
- wordpress - “阅读更多”和“提交”按钮的 Wordpress Polylang 翻译
- javascript - 在 php echo javascript 中使用 onclick
- email - 验证电子邮件地址的最佳方法
- javascript - Swift:WKWebview JavaScript 执行返回了不支持类型的结果
- kibana - 在kibana中获取绝对日期范围的值
- java - 如何使用 sharedpreference 将 favorite_List Activity 添加到 android 中的 ListView 活动
- javascript - Select2 未正确渲染