Display an array that is constantly changing using Vue

As a newcomer to Vue, I have some questions. I am displaying a table with data retrieved from a web service. The issue is that the amount of data received varies each time. The data comes in an array format, such as:

var todos = [
    {name : "dexter" , color : "orange"},
    {name : "jaime", color : "green" },
    {name : "stack", color : "yellow" },
    {name : "overflow", color : "black" }
]

However, sometimes I receive only 2 items in the response. Currently, I need to explicitly specify which item in the array to display. I want to dynamically call and display all items in the array.

var todos = [

  {
    name: "dexter",
    color: "orange"
  },
  {
    name: "jaime",
    color: "green"
  },
  {
    name: "stack",
    color: "yellow"
  },
  {
    name: "overflow",
    color: "black"
  }
]



var i = 0;
var sixthTable = new Vue({

  el: '#sevenTable',
  data: {
    currentPage: 1,
    elementsPerPage: 3,
    ascending: false,
    sortColumn: '',
    rows: [

      {
        name: todos[0].name,
        color: todos[0].color
      },
      {
        name: todos[1].name,
        color: todos[1].color
      },
      {
        name: todos[2].name,
        color: todos[2].color
      },
      {
        name: todos[3].name,
        color: todos[3].color
      }
    ]
  },
  methods: {
    "sortTable": function sortTable(col) {
      if (this.sortColumn === col) {
        this.ascending = !this.ascending;
      } else {
        this.ascending = true;
        this.sortColumn = col;
      }

      var ascending = this.ascending;

      this.rows.sort(function(a, b) {
        if (a[col] > b[col]) {
          return ascending ? 1 : -1
        } else if (a[col] < b[col]) {
          return ascending ? -1 : 1
        }
        return 0;
      })
    },
    "num_pages": function num_pages() {
      return Math.ceil(this.rows.length / this.elementsPerPage);
    },
    "get_rows": function get_rows() {
      var start = (this.currentPage - 1) * this.elementsPerPage;
      var end = start + this.elementsPerPage;
      return this.rows.slice(start, end);
    },
    "change_page": function change_page(page) {
      this.currentPage = page;
    }
  },
  computed: {
    "columns": function columns() {
      if (this.rows.length == 0) {
        return [];
      }
      return Object.keys(this.rows[0])
    }
  }
});
// CSS code snippet here...
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<div id="sevenTable">
  <table>
    <thead>
      <tr>
        <th v-for="col in columns" v-on:click="sortTable(col)">{{col}}
          <div class="arrow" v-if="col == sortColumn" v-bind:class="[ascending ? 'arrow_up' : 'arrow_down']"></div>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="row in get_rows()">
        <td v-for="col in columns">{{row[col]}}</td>
      </tr>
    </tbody>
  </table>
  <div class="pagination">
    <div class="number" v-for="i in num_pages()" v-bind:class="[i == currentPage ? 'active' : '']" v-on:click="change_page(i)">{{i}}</div>
  </div>

This is my complete code, although the array used is not actually a web-service response, it's simplified for demonstration purposes.

Thank you in advance.

Answer №1

Simply input the information provided by the web service directly into your data as shown below:

rows: todos

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

There appears to be an issue with Google Analytics not generating __utm.gif requests, yet no error messages are

I'm encountering an issue with implementing Google Analytics. Despite extensive research, I haven't been able to find a resolution. My objective is to include the user's email address as a custom variable in Google Analytics. I have integra ...

What is the best way to execute individual API requests for various sheets within the same spreadsheet?

I am currently working on integrating the Google Sheets API with Node.js. I need assistance with understanding the correct syntax for calling two separate sheets within one spreadsheet. After reaching out to chatgpt and gemini, I received conflicting answe ...

Error occurred when trying to set the method in the Magento checkout: Uncaught TypeError - Unable to access the 'style' property of null

After deciding to move my Magento 1.3 template to Magento 1.9, I anticipate encountering a lot of minor issues. However, one specific problem has left me stumped. The issue arises when I am in the on-page checkout process and opt to make a purchase as a g ...

Tips for dissecting complex JSONP structures with JavaScript

I have recently come across a valid jsonp structure that I am attempting to parse. However, I am struggling to figure out how to access the videos elements within it. Can anyone provide guidance on how to reference these elements (sources, thumb, title) in ...

How can I access data from the CIA World FactBook using REST, SOAP, or API?

Is there a more efficient method to gather information from the CIA World Factbook without having to download a large dataset? Perhaps the CIA simply collects data. :-) I came across an outdated JAVA package for retrieving information, but I prefer a more ...

Navigating through the map function within Protractor

In my Angular application, I have implemented a timeline that displays event dates with their respective descriptions. Below is the HTML source code for this feature: <!-- timeline --> <h4 class="font-thin m-t-lg m-b-lg text-primary-lt">Hi ...

Sending a batch of files through an axios request by passing them as an object

I need to send multiple images in a specific format through an API call { "date":"currentDate", "files":[Files uploaded via input box] } Here is my approach: Method 1 const event = document.querySelector("#files"); const f ...

Arrangement of data in a max-heap structure

Assuming that A [1 .. n] is a max-heap, the larger elements of the array could be found in various positions such as the second, third, fourth, and beyond. [1] [2] [3] [4] [5] [6] [7] ...

Creating an "Empty" Label Tag without a Name

I've just finished coding a JavaScript calculator and now I need to add three labels to it: "First Number", "Second Number", and a Sum label. My issue is that I don't want the "Sum" label to appear to the left of the text box. Here's the HTM ...

Exploring the Integration of jQuery AJAX in a Contact Form

I would like to incorporate AJAX functionality into a contact form. Here is the current code I have... $("#contact_form").validate({ meta: "validate", submitHandler: function (form) { $('#contact_form').hide(); ...

Unexpected Outcome Arises When Applying Lodash's Debounce Function to Axios API Call

I keep encountering an issue with my app where it updates every time text is typed. I've implemented debounce on an axios request to queue them up until the timer runs out, then they all go at once. But I want to limit the requests to one per 10-secon ...

Tips for generating JSON data in the correct format dynamically while continuously adding new information to the existing object

In my form, users input their email and password, which then generates dynamic JSON upon submission. However, I encountered an issue where the JSON gets corrupted when logging in with different user details as it updates the existing JSON with a new object ...

Choosing Select2 to send in placeholder choices

I have a large dropdown list of postal numbers that is difficult to scroll through with a regular dropdown. To address this issue, I decided to implement Select2 jQuery (version 4) dropdown, which includes a search function. However, due to the size of the ...

Transmitting a jQuery array from the client to the server using AJAX in

I've looked at so many posts about this issue, but I still can't get my code to work. My goal is to retrieve a PHP array of values from the checkboxes that are checked. Here is my code snippet: <!doctype html> <html> <head> & ...

Displaying dates in Meteor Handlebars using `{{ timestamp }}` braces

Looking to shorten the timestamp output in Meteor's Handlebar bracers. How can you convert {{ timestamp }} from Thu Jul 25 2013 19:33:19 GMT-0400 (Eastern Daylight Time) to just Jul 25? Attempted using {{ timestamp.toString('yyyy-MM-dd') } ...

Determine which checkbox is currently selected in Vue and send corresponding data based on the checked status

A radio form that is conditionally disabled by another checkbox. One radio button can send either true or false and the other has an input that sends some data. How can I determine which radio button is checked and decide whether to send true/false or the ...

Using the power of AJAX, retrieve data from a PHP script and showcase the response within

Within my HTML file, I have implemented a feature that allows users to input a value. To validate this input, I created a PHP script that checks if the entered value exists in the database. The script returns the following JSON response: {"active":true} ...

Storing the options' ids in an array within a select box using JavaScript: tips and tricks

Check out this snippet of HTML code: <select id="s1"> <option value="volvo" id="o1">Volvo</option> <option value="saab" id="o2">Saab</option> <option value="opel" id="o3">Opel</option> <option value="au ...

Trouble with Excel Office Script setInterval functionality

Trying to automatically recalculate an Excel worksheet every second using Office Script. Unfortunately, my initial approach did not succeed. function sendUpdate(sheet: ExcelScript.Worksheet) { console.log('hi'); sheet.calculate(true); } func ...

Printing array the last element in C++ programming

Currently, I am developing a dice game in C++ and have implemented arrays in my program. die[5] = { (rand()%6)+1, (rand()%6)+1, (rand()%6)+1, (rand()%6)+1, (rand()%6)+1 }; After initializing the arrays, I display their values using cout<<"First di ...