Using Vue.js to loop through dynamic arrays with v-for

In order to showcase multiple HTML tables of tools, where each table represents a category and each row in the table represents a tool.

data() {
    return {
      cats: '',
      tools: [],
    };
  },
  methods: {
    getToolCats() {
      var rez = getToolCats();
      rez.then(data => this.receiveCats(data) ) 
    },
    receiveCats(_cats){
      this.cats = _cats;
      _cats.forEach(cat => {
        getToolsByCat(cat.href).then(data => this.tools[cat.href] = data);
      });
      console.log(this.tools);
    },
  },
  mounted() {
    this.getToolCats();
  },

The 'cats' (categories) array is filled with data retrieved from an API call. Subsequently, for each category, an API call fetches the list of tools belonging to that category, which are then stored in the 'tools' array using 'this.tools[cat.href] = data'.

Below is the code snippet for displaying the tables:

<div v-for="cat in cats" :key="cat.href" class="tbox col-xs-12 col-sm-6">
    ....
    <table class="table table-hover">
        <tr v-for="tool in tools[cat.href]" :key="tool.href">
            <td>...</td>
        </tr>
    </table>
    ....
</div>

When trying to use a single variable to store the tool list, everything works fine. However, since the number of categories is unknown, creating a variable for each category becomes unfeasible.

Potential issue lies here:

  • Using an array in v-for without a key being defined at the mounted state:

v-for="tool in tools[cat.href]

Any assistance on this matter would be greatly appreciated!

Answer №1

Vue cannot automatically detect when a dynamic property is added in this.tools[cat.href] = data, but it will recognize the change if you use this.$set or Vue.set like this:

this.$set(this.tools, cat.href, data)
:

new Vue({
  el: '#app',
  data() {
    return {
      cats: [],
      tools: {}, // <-- make this an object (not an array)
    };
  },
  mounted() {
    this.getToolCats();
  },
  methods: {
    getToolCats() {
      // setTimeout to simulate delayed API calls...
      setTimeout(() => {
        this.cats = [
          { href: 'https://google.com' },
          { href: 'https://microsoft.com' },
          { href: 'https://apple.com' },
          { href: 'https://amazon.com' },
        ];
        this.cats.forEach((cat, i) => {
          setTimeout(() => {
            const data = { href: cat.href };
            this.$set(this.tools, cat.href, data); // <-- use this.$set for dynamic property addition
          }, i * 1000);
        })
      }, 1000);
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3c5c6d6f3819d869d8284">[email protected]</a>"></script>

<div id="app">
  <div v-if="!cats || cats.length == 0">Loading...</div>
  <div v-for="cat in cats" :key="cat.href" v-else>
    <table>
      <tr v-for="tool in tools[cat.href]" :key="tool.href">
        <td>cat.href: {{cat.href}}</td>
      </tr>
    </table>
  </div>
  <pre>tools: {{tools}}</pre>
</div>

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

Specific category of location on Google Maps

I am currently building an application using Cordova and Ionic. I need to implement a map in my app that will display only specific establishments, such as police stations or doctors' offices. This is the code I have so far: var posOptions = {time ...

How can I send a form without having the page reload using a combination of AJAX, PHP

I am struggling to submit a form without refreshing the page. I have tried using ajax as mentioned in some resources, but it's not working for me. What could be the issue? When I use the following code, everything works fine with PHP: document.getEl ...

Mastering the settimeout function for rotating a cube in three.js: Best practices and tips

I am currently developing a program that will rotate a cube based on quaternion data inputted by the user via a CSV file in an HTML format. The JavaScript code cycles through each quaternion in the dataset, applying them to the cube at regular intervals to ...

Tips on transmitting checkbox data from AJAX to PHP

I'm currently working with this code and facing an issue where data from checkboxes is being sent to PHP one by one. I want to be able to send multiple selected data at once. How can I modify the code to achieve this? $('#lunas').click(funct ...

Using ReactJS in conjunction with MaterialUI version 3, implement a select feature directly within a

Currently utilizing Reactjs along with MaterialIU version 3 (not to be confused with v4), my objective is to create a Table by employing [array].map method, and embed a Select inside each TableCell. The aim is to assign a specific percentage separately for ...

What is the method to access the state within a function?

In my project, I have two important files - post.js and index.js. The post.js file is responsible for managing the initial state, while the index.js file handles the saga's API. However, I encountered a scenario where I needed to access the state ev ...

Error encountered while attempting to save process using ajax - 500 Internal Server Error

I am facing an issue with my CodeIgniter code where I encounter a 500 internal server error when trying to save data. I am not sure why this problem is happening and would appreciate any help. Below is the AJAX code in the view: function save() { $(& ...

In what situation is a generic array completely indispensable -- a prime example

Is there a situation where the use of a generic array is absolutely necessary? Generics and arrays do not always work well together. Are there any instances where an ArrayList cannot be used, and a generic array is the only solution? Effective Java sugg ...

Guide for implementing tabs using router-view in Vue.js

I've been utilizing vuesax [ https://github.com/lusaxweb/vuesax ] for managing tabs. Within vs-tabs, I have multiple router-views. I am looking to display different Vue template files for each respective tab of the router-view. Below is the code snip ...

In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true. const Ids = ['743156', '743157'] [ { "id&quo ...

Understanding React: Why 'props' Property Cannot Be Read

Recently, I made the decision to delve into learning React and chose to begin with the official tutorial. Everything was going smoothly until I reached a specific portion of my code: var CommentBox = React.createClass({ render: () => { return ( ...

Having trouble displaying a pre-designed 3D model in three.js

I would greatly appreciate it if someone could provide an example and elaborate on how to render a 3D object using three.js or similar libraries. The model already exists, so the focus is solely on rendering it effectively. Can you please guide me throug ...

The execution of a nested object's function that calls a JavaScript function encounters an error

Below is a simple example demonstrating the issue I am facing, which you can also view on JSFiddle here. While I understand why the issue is happening, I'm unsure of how to resolve it without altering the existing JS structure. The problem arises wh ...

The currency value should always be a positive number and can have up to two decimal places, separated by a period

Whenever I incorporate the vue-paypal-check: <PayPal amount="amount" currency="USD" :client="credentials" env="sandbox" > </Paypal> ... computed: { amount() { var total_price = Number(this.product_ ...

Check a numpy array for any lists containing at least one value from a previous row, and filter out those lists

Working with a numpy array b = np.array([[1,2], [3,4], [1,6], [7,2], [3,9], [7,10]]) The task at hand is to reduce the array b. The reduction method involves examining each element in b, such as [1,2], and removing all elements in b that contain either ...

What strategies can be employed to reduce the need for numerous if-else statements in my JavaScript code?

In my input form, users have the ability to make edits. I need to send only the data that has been changed by the user. Currently, I am repeating the same lines of code multiple times to compare and determine what data needs to be sent. Is there a more e ...

Combine multiple arrays of strings into one array using Dataweave mapping

I need to transform an array with a single index containing a JSON object with three different string arrays. My goal is to map each index from the arrays into a single JSON object based on their position, combining them into one cohesive output. Can this ...

Style selector for dynamic drop-down menus

import React, { Component } from "react"; export default class FontChanger extends Component{ constructor(props){ super(props); this.state ={ selectedFont: "", currentFont: "", }; this.handleFon ...

Can a client-side React component or application be hosted on a server-side Express route?

Currently, I have a Node/Express backend that utilizes Pug.js to render various server-side routes for a basic, static website. In React.js, I have developed an interactive "builder" component through CRA, enabling visitors to configure products interacti ...

Using THREE.js to animate between two specific points on a spherical object

Seeking a solution on how to rotate a sphere in order to align one specific point with another on the surface, like illustrated in the image below. An illustration of the desired movement While I've come across tutorials explaining this process i ...