Jos*_*ers 2 vue-router axios vuejs2
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')',
I get an error: 'homepage.vue?3ec6:72 Uncaught (in promise) TypeError: Cannot read property '$router' of undefined'.
但是,如果我在axios调用之外的方法顶部使用相同的路由,则可以正常工作。
那我在这里想念什么?
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);
})
}
Run Code Online (Sandbox Code Playgroud)
您必须定义this外部axios方法,因为this内部axios指向axios对象,而不是vue组件:
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');
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8564 次 |
| 最近记录: |