You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js循环中调用方法报错:无法读取calculateDistance属性

Vue方法调用报错原因与解决办法

报错原因

在mapDrag方法的forEach回调中使用了普通function,该函数内部的this指向发生改变,不再指向Vue实例,导致无法读取到calculateDistance方法。

解决方案

方案1:使用箭头函数

箭头函数不绑定自身的this,会继承外层作用域的this(即Vue实例):

mapDrag: function () {
   let lat = 100;
   let lng = 200;
   this.cities.forEach((city, index, array) => {
      let distance = this.calculateDistance(city.latitude, city.longitude, lat, lng)
      console.log(distance)
   });
}

方案2:提前保存Vue实例的引用

在forEach外部将Vue实例的this保存为变量,回调中使用该变量调用方法:

mapDrag: function () {
   let lat = 100;
   let lng = 200;
   const vm = this; // 保存Vue实例引用
   this.cities.forEach(function (city, index, array){
      let distance = vm.calculateDistance(city.latitude, city.longitude, lat, lng)
      console.log(distance)
   });
}

方案3:利用forEach的第二个参数绑定this

forEach支持传入第二个参数作为回调函数的this指向:

mapDrag: function () {
   let lat = 100;
   let lng = 200;
   this.cities.forEach(function (city, index, array){
      let distance = this.calculateDistance(city.latitude, city.longitude, lat, lng)
      console.log(distance)
   }, this); // 绑定this为Vue实例
}

内容的提问来源于stack exchange,提问作者Hai Truong IT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:20:59