【问题标题】:Vuejs error call other function within loopVuejs错误在循环内调用其他函数
【发布时间】:2022-10-14 18:03:16
【问题描述】:

我有一个带有数据的示例代码是城市包括对象(纬度,经度)

这是我的代码

...
   methods: {
      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)
         });
      },
      calculateDistance: function (lat1, long1, lat2, long2) {
            //radians
            lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0;
            long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0;
            lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0;
            long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0;


            // use to different earth axis length
            var a = 6378137.0;        // Earth Major Axis (WGS84)
            var b = 6356752.3142;     // Minor Axis
            var f = (a-b) / a;        // "Flattening"
            var e = 2.0*f - f*f;      // "Eccentricity"

            var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 )));
            var cos = Math.cos( lat1 );
            var x = beta * cos * Math.cos( long1 );
            var y = beta * cos * Math.sin( long1 );
            var z = beta * ( 1 - e ) * Math.sin( lat1 );

            beta = ( a / Math.sqrt( 1.0 -  e * Math.sin( lat2 ) * Math.sin( lat2 )));
            cos = Math.cos( lat2 );
            x -= (beta * cos * Math.cos( long2 ));
            y -= (beta * cos * Math.sin( long2 ));
            z -= (beta * (1 - e) * Math.sin( lat2 ));

            return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000);
        },
   },
...

在方法上的函数 mapDrag 中,错误显示:

[Vue warn]: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'calculateDistance')"

【问题讨论】:

  • this 与这里的功能范围有关。试试这个this.cities.forEach((city, index, array) =>

标签: javascript vue.js vuejs2


【解决方案1】:

使用箭头函数调用,如。

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

this 将与调用函数的范围绑定。所以把它写成一个普通的函数会占用Array.forEach的范围。要获得组件范围,您必须将其用作箭头函数。

【讨论】:

  • 谢谢@Nitheesh
  • @HaiTruongIT 如果这是您要找的,请批准答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2018-06-13
  • 1970-01-01
  • 2014-01-11
相关资源
最近更新 更多