Unable to run for loop in vue.js

Hello, I'm a newcomer to using Vue.js and am encountering an issue with executing a simple for loop in my code. Any assistance or guidance would be greatly appreciated. Here is the snippet of my code:

var Vue = require('vue');
Vue.use(require('vue-resource'));
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
new Vue({

    el: '#adresponse',

    ready: function() {
        this.fetchMessages();
    },

    data: {
        classified_bids: {},
        accept_qty: {},
        submitted: false
    },

    methods: {
        fetchMessages: function () {
            this.$http.get('/api/getbids')
                .success(function (bids) {
                    this.classified_bids = bids;
                    for (i = 0; i < this.classified_bids.length; i++) {
                        this.accept_qty[i] = 0;
                    }
                });
        }
    }
});

Answer №1

After making a small adjustment to the for loop, I was able to get it to function properly:

el: '#resultad',

ready: function() {
    this.retrieveData();
},

data: {
    categorized_offers: {},
    total_amount: {},
    completed: false
},

methods: {
    retrieveData: function () {
        this.$http.get('/api/fetchoffers')
            .success(function (offers) {
                this.categorized_offers = offers;
                for (var index in this.categorized_offers) {
                    this.total_amount[index] = 0;
                }
            });
    }
}

});

Answer №2

The issue at hand revolves around the context of this within the .success() callback function.

A potential solution could involve modifying your code as shown below:

this.$http.get('/api/fetchdata')
  .then((response) => {
    this.data = response.data;
    for (let i = 0; i < this.data.length; i++) {
      this.processedData[i] = 0;
    }
  })
  .catch((error) => {
    console.error('An error occurred: ' + error);
  });

For further insights, you may find this related discussion helpful.

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

Headers error encountered during sending request

When making a request with this method, an error labeled as "[ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client" occurs. I recently started learning about express and might have made some progress. Can you please help me identif ...

How to Make a Zigzag Formation in three.js?

I have been working on developing a 3D tool and was in need of a zigzag structure. I managed to create it by iterating a function that produces 'V' multiple times, but now I am looking for a way to achieve the same effect using a single geometry ...

What is the most efficient way to restrict multiple input fields, each using v-model, to only accept numeric values in Vue.js without duplicating code for every input field?

I have several input fields in Vue.js that I want to restrict to only accept numbers. I want to prevent users from entering any characters except digits from 0-9. I managed to achieve this successfully with a solution that is resistant to copy-paste: C ...

Using jQuery checkboxes with ajax for data submission and storage in PHP without the need for insertion

Seeking guidance on how to properly serialize elements value instead of pushing it, as I am encountering an issue where each value is being inserted into the database 9 times. Any assistance in figuring out this problem would be highly appreciated. The HT ...

Next.JS - What is the reason behind data fetching occurring on both the server and client side?

When I call a regular fetch function in the index.js component and then log the response to the console, something unexpected happens. Despite the fetch being inside the component function, the response is also logged on the server side: it shows up in the ...

Guide on setting a value in $(document).ready using code behind

I am currently working on a .NET application with the use of Twitter Bootstrap. My main challenge right now is retrieving data from a .aspx.cs page to a .aspx page. Here's a look at my code: strObject.cs public class strObject { public string Nam ...

The scroll() function in jQuery does not bubble up

Recently, I encountered an issue with a Wordpress plugin that displays popups on scroll. The code I currently have is as follows: jQuery(window).scroll(function(){ //display popup }); The problem arises with a particular website that has specific CSS ...

struggling to send variables to jade templates with coffeescript and express.js

As a newcomer to node and express, I am currently building the front end of an application that utilizes jade as its templating engine. Despite extensive searching online and within this community, I have not been able to find a solution to a particular is ...

Transforming an interactive HTML webpage into React/JSX

Imagine a scenario where I have two files: example.html <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="u ...

regex execution and testing exhibiting inconsistent behavior

The regex I am using has some named groups and it seems to match perfectly fine when tested in isolation, but for some reason, it does not work as expected within my running application environment. Below is the regex code that works everywhere except in ...

Omit words from list in a route in Express.js

When working with the Express.js Framework, I am faced with a scenario where I have the following route defined: app.post('/:username/:slug', user.fn); I am now looking for a solution to create a regular expression that can validate if the slug ...

Exploring the functionality of arrays in Jest's cli option --testPathIgnorePatterns

Looking to exclude multiple folders, one in the src folder and another in node_modules, when using the --testPathIgnorePatterns option. Does anyone have an example of how to use this pattern effectively? I am unable to configure an array in the package.js ...

The Facebook messenger checkbox plugin does not appear to be displaying correctly

I have integrated the Facebook Messenger Checkbox Plugin into my AngularJS application by following the guide provided at this link. Initially, I was able to successfully display the messenger checkbox plugin on a page. However, upon navigating to another ...

preserving the status of checkboxes based on an array of binary values

I am trying to figure out how to restore the state of checkboxes in an ORACLE APEX tabular form. The selection is made in the first column using the APEX row selector f01. After saving the checkbox state in a collection and then transferring it to an arra ...

Incorporating JSON data seamlessly into a visually appealing Highcharts pie chart

It seems like I'm facing a minor issue here. Everything was working fine until... $(document).ready(function() { // Original data var data = [{ "name": "Tokyo", "y": 3.0 }, { "name": "NewYork", "y": 2.0 }, { "name": "Berlin", ...

Encountering an issue with extending the MUI color palette, receiving a "reading 'dark'" error due to properties of undefined

Encountering an issue when trying to expand the MUI color palette—getting this error instead: Error: Cannot read properties of undefined (reading 'dark') Take a look at my theme.ts file below: const theme = createTheme({ palette: { pri ...

Issue with parentNode.replaceChild not functioning properly in Internet Explorer 6

In my HTML file created with FCK editor, I attempted to replace an existing table element with a new one using the parentNode.replaceChild method. While this change was successful in Internet Explorer 8, it resulted in errors when viewed in IE6 and IE7. ...

Trigger a fixed bottom bar animation upon hover

I have a bar fixed to the bottom of the browser that I want to hide by default. When a user hovers over it, I want the bar to be displayed until they move their cursor away. <!doctype html> <html> <head> <meta charset="utf-8"> &l ...

Retrieving data response post upload with JQuery and an HTML5 Uploader

After uploading an image and receiving a successful post response with the id of the inserted image, how can I insert this response as a data-id attribute within a a tag? Where in the function does this process occur? Here is the function: function img_ ...

Chronological Overview (Highcharts)

Can you customize a timeline in Highcharts to resemble the image? https://i.sstatic.net/5Lipu.png I have a functional example of the timeline I desire, but the color coding and filtering aspects are challenging for me. I am attempting to apply a filter th ...