Home > Enterprise >  Vuejs error call other function within loop
Vuejs error call other function within loop

Time:10-17

I have a sample code with data is cities include object(latitude, longitude)

This is my code

...
   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);
        },
   },
...

When in function mapDrag on methods, error show:

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

CodePudding user response:

Call using arrow function like.

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

this will be bounded with the scope from which the function is being called. So writing it as a normal function will take the scope of Array.forEach. To get the component scope you have to use it as an arrow function.

  • Related