使用vue在axios响应后重定向 [英] redirect after axios response with vue
问题描述
好的,所以我有以下方法.基本上,我正在调用一个API后端,发布用户名和密码,如果通过,则在响应中,服务器会向我发送200状态.我想做的是在响应中,获得状态后,运行if/else,因此如果状态为200,则重定向,否则显示错误消息.每次我尝试使用'this.$ router.push('/此处的任何路线')'
Ok, so i have the following method. Basically I am calling an API backend, posting username and password, and if those pass, in the response, the server sends me a 200 status. What I want to do, is in the response, after I get the status, run an if/else, so if the status is 200, redirect, else display an error message. every time i try to use 'this.$router.push('/any route here')',
我得到一个错误:'homepage.vue?3ec6:72未捕获(承诺)TypeError:无法读取未定义的属性'$ router'.
I get an error: 'homepage.vue?3ec6:72 Uncaught (in promise) TypeError: Cannot read property '$router' of undefined'.
但是,如果我在方法顶部使用相同的路由,则在axios调用之外,它将正常工作.
But if i use the same route at the top of the method, outside the axios call, it works fine.
那我在这里想念什么?
hero_login: function(event){
event.preventDefault();
axios.post('API call here',
{
service:'client',
user: this.user_email,
password: this.user_password,
json:true
})
.then(function(response){
const status =
JSON.parse(response.data.response.status);
console.log(status);
})
}
推荐答案
您必须在axios方法外部定义this
,因为axios内部的this
是指axios对象,而不是vue组件:
You have to define this
outside axios methods because this
inside axios refers to the axios object, not the vue component:
hero_login: function(event) {
let self = this;
event.preventDefault();
axios.post('API call here',
{
service:'client',
user: this.user_email,
password: this.user_password,
json:true
})
.then(function(response){
const status =
JSON.parse(response.data.response.status);
//redirect logic
if (status == '200') {
self.$router.push('/any route here');
}
})
}
}
这篇关于使用vue在axios响应后重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!