使用 vue 在 axios 响应后重定向 [英] redirect after axios response with vue
问题描述
好的,所以我有以下方法.基本上我正在调用 API 后端,发布用户名和密码,如果这些通过,在响应中,服务器向我发送 200 状态.我想要做的是在响应中,在获得状态后,运行 if/else,因此如果状态为 200,则重定向,否则显示错误消息.每次我尝试使用 'this.$router.push('/any route here')',
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 Uncaught (in promise) TypeError: Cannot read property '$router' of undefined'.
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.
那么我在这里错过了什么?
So what am i missing here?
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屋!