最近写代码的时候发现了一个很是神奇的事情,在axois中再嵌套一层axios调接口的时候get报错了,在比对代码之后发现代码没有问题,之后查阅了一些资料之后发现是this指向的问题~~ 在箭头函数中this的指向已经不是vue实例了,而是变成了window~
问题一 this指向
错误代码
renderMesh(map) {
//地图渲染
this.$axios
.get(this.httpApi + "/api/Main/GetBlockMap", {})
.then(res => {
if (json.length > 0) {
this.$axios.get(_this.httpApi + "/api/Main/GetGridInfo", {})
.then(function(res){
console.lgo(res)
})
.catch(function(err){
console.log("请求失败233");
});
}
.catch(err => {
console.log("请求失败233");
});
},
问题描述:因为在外层的axios成功的回调函数中使用的是箭头函数,所以内层的this.$axios.get()中的this指向发生了变化,指向了window,那winodw中是没有$axios这个函数方法的,所以就报错了,
解决方案:
在renderMesh()函数内将this指向赋值给某个变量(如_this),然后将内层的axios改为 _this.$axios.get这样问题就解决了
renderMesh(map) {
let _this = this;
//地图渲染
this.$axios
.get(this.httpApi + "/api/Main/GetBlockMap", {})
.then(res => {
if (json.length > 0) {
_this.$axios.get(_this.httpApi + "/api/Main/GetGridInfo", {})
.then(function(res){
console.lgo(res)
})
.catch(function(err){
console.log("请求失败233");
});
}
.catch(err => {
console.log("请求失败233");
});
},
vue生命周期钩子函数中的this指向的是vue实例,如created,mounted,methos...
但是箭头函数(=>)中的this指向是winodow!
问题二 箭头函数中new不起作用
问题描述:我在axios请求成功的回调函数使用了高德地图的信息窗功能,然后发现报错了~~~ 但是将这段代码挪到axios请求的外面又不报错了,通过各种折腾,然后发现在是因为箭头函数中不能使用new,,,,,,,,,,
坚决方案:嗯,简单粗暴的将"=>res"换成了function(res)之后问题就解决了~~~~~
有问题代码
this.$axios.get(_this.httpApi + "/api/Main/GetGridInfo", {})
.then(res =>{
var infoData = eval("("+ res.data +")")
var infoWindow2 = new AMap.InfoWindow({ //点击的时候打开地图提示窗
autoMove: true,
content: openInfo(infoData,gridName)
});
infoWindow2.open(map, polygon3.getBounds().getCenter())
})
.catch(err =>{
console.log("请求失败233");
});
修改后代码
this.$axios.get(_this.httpApi + "/api/Main/GetGridInfo", {})
.then(function(res){
var infoData = eval("("+ res.data +")")
var infoWindow2 = new AMap.InfoWindow({ //点击的时候打开地图提示窗
autoMove: true,
content: openInfo(infoData,gridName)
});
infoWindow2.open(map, polygon3.getBounds().getCenter())
})
.catch(function(err){
console.log("请求失败233");
});
解决~~~~~~