axios请求中$router失效(undefined)的问题
先上代码
methods: {
logOut() {
this.$axios.post("/logout").then(function (response) {
console.log(response);
if (response.data.code == 200) {
success("注销成功");
this.$router.push({ path: "/" });
} else {
error("错误!请刷新重试");
}
});
},
},
但在页面显示就是
解决办法就是:
在**.then里面加入.bind(this)**
methods: {
logOut() {
this.$axios.post("/logout").then(function (response) {
console.log(response);
if (response.data.code == 200) {
success("注销成功");
this.$router.push({ path: "/" });
} else {
error("错误!请刷新重试");
}
}.bind(this));
},
},
或者可以将promise中的function()更换为箭头函数
为什么
主要是作用域的问题引起的,axios返回的是一个promise对象,this指向的不是vue实例而是这个promise对象,结果就会导致undefined
顺便指个路:作用域讲解