What is the best way to iterate over an array of objects using v-for in Vue.js?

Having trouble looping through this array of objects. Everything seems fine but the data is not showing up on the console.

{
 "messages":[
  {
    "id":1,
    "sender":"frank",
    "message":"Lorem ipsum...",
    "time":1398894261,
    "status":"read"
  },
  {
    "id":2,
    "sender":"mary",
    "message":"Lorem ipsum...",
    "time":1390824261,
    "status":"read"
  },
  {
    "id":3,
    "sender":"john",
    "message":"Lorem ipsum...",
    "time":1308744200,
    "status":"unread"
  }
 ]
}

Struggling to iterate through the data received from an http get request. The data is being fetched but not being looped. Below is the JavaScript code:

new Vue({
    el: '#app',
    data: '',
    ready: function() {
      // GET request
      this.$http.get('https://www.example.com/file.json', function (data) {
        // set data on vm
        this.$set('data', data.messages);
        }).error(function (data, status, request) {
            console.log('http request error')
        })
    }
  })

Here is the corresponding HTML:

<div v-if="data">
  <li v-for="d in data">{{ d.sender }}</li>
</div>
<p>{{data[0].sender}}</p> <!-- this part works -->

Answer №1

When dealing with the callback of an AJAX request, remember that `this` is NOT referring to the Vue instance. There are a few ways to address this issue:

  1. Using arrow functions
  2. Declaring `var vm = this`
  3. Using `.bind(this)`

Check out this example on how to use arrow functions: https://codepen.io/iampaul83/pen/bYpqgm

Using arrow function:

new Vue({
    el: '#app',
    data: '',
    ready: function () {
        // Making a GET request
        this.$http.get('https://www.example.com/file.json', (data) => {
            // Setting the data on vm
            this.$set('data', data.messages);
        }).error(function (data, status, request) {
            console.log('HTTP request error')
        })
    }
})

Declaring `var vm = this`:

new Vue({
    el: '#app',
    data: '',
    ready: function () {
        // Making a GET request
        var vm = this
        this.$http.get('https://www.example.com/file.json', function (data) {
            // Setting the data on vm
            vm.$set('data', data.messages);
        }).error(function (data, status, request) {
            console.log('HTTP request error')
        })
    }
})

Using `.bind(this)`:

new Vue({
    el: '#app',
    data: '',
    ready: function () {
        // Making a GET request
        this.$http.get('https://www.example.com/file.json', function (data) {
            // Setting the data on vm
            this.$set('data', data.messages);
        }.bind(this)).error(function (data, status, request) {
            console.log('HTTP request error')
        })
    }
})

Answer №2

If you are encountering issues with deep reactivity limitation in vue.js, I recommend referring to the official vue documentation for guidance. Instead of utilizing this.$set, I suggest utilizing the push method to iterate through your response and add each result individually to a messages variable defined in your data object.

data.messages.forEach( (msg ) => { 
     this.messages.push( msg ); 
}

Once you have populated the messages variable, be sure to iterate through it in your template.

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

Avoiding caching when making requests to /api/ routes in VueJS Progressive Web Apps (PWA

I recently developed a Vuejs project with PWA capabilities, but encountered an issue when building its production version. The project seems to be using cached versions of API requests instead of making fresh network calls. I am trying to find a way to eit ...

Tips for dividing an array based on a defined regex pattern in JavaScript

I want to split a string of text into an array of sentences while preserving the punctuation marks. var text = 'This is the first sentence. This is another sentence! This is a question?' var splitText = text.split(/\b(?<=[.!?])/); split ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...

positioning newly generated dropped elements within the DOM structure dynamically

Hello everyone, I have a query related to drag and drop functionality. I am currently working on an application that allows users to create websites using only drag and drop features. I am facing a challenge in implementing a feature where users can drop e ...

Achieving Horizontal Alignment of Tab Labels and Icons in Material-UI with Tabs API

I am currently attempting to customize the Material UI CSS in order to align both the phone icon and text on the same line and closer together. After doing some research, I stumbled upon the Tabs API which seemed promising. Upon further inspection, I disc ...

Completing the regex properly

When using my editor, I am able to paste a video URL which is then converted by regex into an embed code. The URL in the WYSIWYG-editor looks like this: Once converted, the output HTML appears as: <p>http://emedia.is.ed.ac.uk:8080/JW/wsconfig.xml& ...

Combining JWT authentication with access control lists: a comprehensive guide

I have successfully integrated passport with a JWT strategy, and it is functioning well. My jwt-protected routes are structured like this... app.get('/thingThatRequiresLogin/:id', passport.authenticate('jwt', { session: false }), thing ...

Setting Json.Net as the primary serialization tool for a WCF REST service involves a few key steps

Is there a way to modify the default behavior of the WCF DataContractSerializer when serializing and deserializing entities in order to use JSON.NET instead? In my service contract, I am working with the City entity which has IsReference=true for design p ...

Should the Bourbon path be added to the package.json file?

Is it possible to integrate Bourbon paths (installed via npm) into a package.json file of a node project? All the examples I have come across involve using grunt, etc: var bourbon = require('node-bourbon'); bourbon.includePaths // Array of Bour ...

Choose the value of the dynamically changing id with the same name using jQuery

Whenever I choose the id (they all have the same id number which is fetched dynamically), it displays the value of the first id. Here's how I'm trying to implement it, but it doesn't seem to be working: function editdr() { qty = $(thi ...

What is the advantage of utilizing AngularJs .constant() over simply declaring a JavaScript const variable?

Currently, I am involved in a project using AngularJS where we have implemented a .constant() provider to define some fundamental details that are utilized throughout the entire project. An example of this would be specifying a cookie name like so: .const ...

get an array of JSON data from a VueJS fetch or axios.get request

I can't seem to figure out this issue. The code I have below is giving me some trouble. When I try to run it, I keep getting the following error message: Access to XMLHttpRequest at 'URL' from origin 'http://localhost:8000' has b ...

Inserting data with special characters from an Ajax POST request into a database

I am facing an issue with my form that contains text inputs. When I use an ajax event to send the values via POST to my database PHP script, special characters like ' " \ cause a problem. If the string contains only numbers/letters and no special ...

How can I dynamically change the default value of the selected option dropdown in React-Select when a new option is chosen?

Can you help me understand how to update the default displayed value on a dropdown in a react-select component? When I choose a different option from one dropdown, the select dropdown value does not change. I've attempted this.defaultValue = option.va ...

techniques for synchronizing web service protocols and documents

I posted this query on programmers, but there hasn't been much activity yet... if this isn't the right place, I may just withdraw the question. Currently, I am in the process of creating a web service (PHP+JSON) to synchronize with my iPhone app ...

Concealing the table border with the help of jQuery

I am working with a dynamically created tables in a ASP.NET repeater, where the number of tables can vary depending on the data retrieved from the database. Below is a sample markup along with the CSS and jQuery code. Please note that the tables are dynami ...

Formatting dates in AngularJS

Is there a way to customize the date format within an ng-repeat loop? I attempted to format it as shown below <div class="col-date">{{row.Calendar.start | date : "dd.MM.y"}}</div> However, it did not produce the desired outcome. What is th ...

Retrieving selected values from a dynamic Primeng checkbox component

Within my Angular app, I am managing an array of questions. Each question includes a text field and an array of string options to choose from. The questions are retrieved dynamically from a service and can be updated over time. To allow users to select mul ...

Encountering an AttributeError while attempting to write an array to a raster file with spatial attributes using the array2raster package, possibly due to

My workflow involves utilizing two different scripts. The first script uses hydrology tools to determine sink depths in a DEM and generates a binary sink/no-sink array. The second script is responsible for labeling pixel groups. To visualize the results sp ...

If someone installs our chat widget on their website using an <iframe> script, I would like the widget to be deactivated when our website is experiencing downtime

We utilize an iframe to create our Chat Widget. One issue we face is that when our main website is down, it causes errors on client websites where the widget is embedded. I am looking for a way to automatically disable the "Chat widget" when our website ...