vue中this指向以及箭头函数中不能使用new

最近写代码的时候发现了一个很是神奇的事情,在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");
});

解决~~~~~~

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值