Calling another function within a loop in Vuejs causes an error

I am working with a code sample that contains data for cities including latitude and longitude values.

Here is the code snippet:

...
   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) {
            // implementation of distance calculation
        },
   },
...

However, when the mapDrag method is called, an error occurs:

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

Answer №1

Utilize arrow functions for calling.

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

this will be bound to the scope where the function is called. Using a regular function will bind it to the scope of Array.forEach. To access the component scope, opt for an arrow function instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Step-by-step guide on setting dates from the selected shortcut using Vue2-datepicker

Our calendar feature is powered by the Vue2-datepicker library, with added shortcuts for user convenience. However, there is an issue where selected dates do not appear on the datepickers when a shortcut is chosen. Any assistance on resolving this matter w ...

Connect hierarchical JSON using AngularJS

I'm facing an issue where I am attempting to bind JSON with two levels to a div using angular.js. The first level binds correctly, but the second level does not seem to be binding properly. Can someone please provide suggestions on how to adjust the b ...

Making adjustments to a row in the free jqGrid is a breeze with the ability

Using free jqGrid 4.12.1, I aim to incorporate functionality for adding, editing, and deleting rows in the grid with server-side calls for each operation. Below is the implementation of editurl and 'actions' formatter, { name: "actions", wi ...

Animating a MakeHuman character using BVH files in Three.js

My goal is to animate a mesh through its skeleton using a BVH file on a webpage. Here's my process: Create a character in MakeHuman and export it (I find mhx format works best). Import the character into Blender. Retarget the character to a BVH usin ...

Having success in FF and Chrome, but encountering issues in IE? What could be causing this disparity

My partner wrote a script, but he is currently offline so I am trying to troubleshoot the issue on my own. Here is the current code we are working with: function checkProgress(Progress) { // Retrieve progress status $.get('http://www.site.c ...

Rearrange JavaScript Object in a Custom Sequence

Looking to filter a JSON Object (Array of Arrays) with a specific order requirement: order: ['Hors','TTC','Total général', 'verger', ' Tra'] data = [[" Tra", "100 - 149 ch", "Total"] [" Tra", "150 - 199 ...

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

Using Vue's $emit method within a Promise

I am currently working on an image upload feature that is based on a Promise. Within the "then" callback, I am attempting to $emit an event named 'success'. Although my VueDevTools shows me that the success event has been triggered, the associate ...

Ignoring break lines in Javascript using regular expressionsKeeping break lines at bay with regular expressions

I need help modifying a regular expression to prevent users from inserting special characters like $ # ?. The current expression I am using is /^((?![#$%^*<>{}!=|/?])\s.)*$/ When I apply this expression on a textarea, Angular throws an error w ...

Verify the uploaded file: Confirm that it is a valid image

Is there a way to determine in JavaScript if the uploaded file is a valid image? <input type="file" name="uploadPicture"/> I am aware that I can check the file extension, but this method is not foolproof since someone could simply change a .txt fil ...

Passing a variable through an ajax request upon successful completion

Is there a way I can include the variable 'schedule_id[i]' in the result of this call? Can I also add this variable to the data object? Here's my code: for (var i = 0; i < schedule_id.length; i++) { //Making an AJAX request $.a ...

When running "npm run build" in Vue.js Vue-cli, the CSS is compiled to set the image opacity to 1%

Executing npm run serve results in everything working correctly. After running npm run build, no errors are reported. Upon viewing the website, I noticed that the images in the gallery section were not visible. Upon inspecting the element, I found that t ...

How can I stop the body from scrolling to 100% height when the virtual keyboard is displayed?

My chat app has sticky header and footer elements. To handle the mobile virtual keyboard opening, I adjust the document's height using window.visualViewport.height. For example, if the browser's height is 1000px and the virtual keyboard takes up ...

Using the match.params.id in React: A step-by-step guide

Having some trouble with my React code. I need to display the product name based on its ID, where the product data is fetched from product.js. I am using a router to switch between different products without reloading the page. import product from './ ...

Troubleshooting node modules for browser compatibility

Looking for assistance with running a specific node module in a browser. The module in question is called fury.js. I attempted to use browserify, however, encountered an error stating "ReferenceError: fury is not defined" when trying to utilize it. In th ...

The Slice method is malfunctioning after the array has been filtered

I am currently working on creating a news portal app using Next JS, Redux, mongoose, and Express. My Issue is: While I am able to filter specific items from an array successfully, I encounter problems when attempting to display a specific number of items, ...

All about the ins and outs of JavaScript and manipulating the

I attempted to use DOM manipulation to change the page background color and div background color by utilizing getElementById and onclick methods. I wrote some code to make this happen, but unfortunately, it did not work as expected. Can anyone identify wh ...

New to WCF: How to Invoke Methods using JavaScript

Hello there! As someone new to WCF, I initially thought it would be similar to ASP.NET web services. However, I'm facing an issue where I am unable to call a method from client-side JavaScript. Here is a snippet of my web form: <form id="form1" r ...

Conceal the sidebar once user is logged in

I need a dynamic webpage; upon loading the login page, the sidebar should be hidden and the login page should occupy the full width of the page. Once the user successfully logs in, the sidebar along with all components should be displayed. I've attemp ...

Can you provide an example of JSON for a MultiStep Form that includes a variety of control types for viewing

Could someone please provide me with JSON examples of multi-step forms that include various types of controls such as radio buttons, checkboxes, dropdown menus, and calendars? I am in need of JSON for both the view and edit forms. Your help would be grea ...