Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button.

<div v-for="(item, index) in items" :key="index">
  <button @click="fetchData(item.id)">Load Data</button>
  <ul v-if="THEDATALOADED">
    <li v-for="(data, index) in THEDATALOADED">
      {{ data.value }}
    </li>
  </ul>
</div>

In addition, it is crucial to maintain all the data associated with each button separately. Reassigning all data by setting this.THEDATALOADED = response.data would cause it to update and display the same data for every v-for iteration whenever any button is clicked.

Answer №1

I suggest you update the fetched data in the corresponding item :

<div v-for="(item, index) in items" :key="index">
  <button @click="fetchData(item.id,index)">Load Data</button>
  <ul v-if="item.THEDATALOADED">
    <li v-for="(data, index) in item.THEDATALOADED">
      {{ data.value }}
    </li>
  </ul>
</div>

within the fetchData method :

 fetchData(id,index){
      ....
      let tmp=this.items[index];
      tmp.THEDATALOADED=response.data;
      this.$set(this.items,index,tmp);
      ...
  }

The provided code demonstrates your scenario, where there is a list of users and each user has their own set of posts. By clicking on the load Posts button, it fetches the posts associated with that user:

new Vue({
  el: '#app',
  data: {
    users: [],
  },
  mounted() {

    axios.get('https://jsonplaceholder.typicode.com/users')
      .then((response) => {
        this.users = response.data
      })
  },
  methods: {
    getPosts(id, index) {
      axios.get('https://jsonplaceholder.typicode.com/posts?userId=' + id)
        .then((response) => {
          let tmp = this.users[index];
          tmp.posts = response.data;
          this.$set(this.users, index, tmp);
        })
    }
  }
})
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8>
  <title></title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://unpkg.com/vue-axios/dist/vue-axios.min.js"></script>
</head>

<body>
  <div id="app">
    <div v-for="(user, index) in users" :key="index">
      <span>{{user.name}}</span>
      <button @click="getPosts(user.id,index)">load Posts</button>
      <ul v-if="user.posts">
        <li v-for="(post, index) in user.posts">
          {{ post.title}}
        </li>
      </ul>
    </div>
  </div>
</body>

</html>

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

The modal is functioning properly on Firefox and Internet Explorer, but it is experiencing issues

Having an issue with my modal not functioning properly in Chrome. When I click on it, only the background fades and both the before and after content load in the Chrome Dev tools simultaneously with no visible content in between. Here is a link to the Cod ...

Utilize the results of the "event's" output as a variable

Struggling with manipulating checkbox values? The `change` event on checkboxes might return an object like this: {"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"} To transform the above object into a format that can be co ...

Problem importing npm module with Meteor 1.3

I've been trying to follow the guide for using npm packages in Meteor 1.3, particularly focusing on installing the moment npm module. However, I can't seem to work it out despite its simplicity. Every time I attempt to use the package in the cli ...

Loading GLTF model via XHR may take an infinite amount of time to reach full completion

I am attempting to load a GLTF model of a piano using XHR and showcase the loading progress on a webpage. The model is being loaded utilizing the Three.js library. On a local server, everything works perfectly - the loading percentage is shown accurately, ...

Vue: Choosing an option during the execution of setInterval

I'm facing an issue where I can't select an option while a setInterval function is running on the page. The main problem is that an option cannot be selected at the same time as the setInterval timer fires. let updateDelay = 100; var vueObj = ...

Tips for aligning the first element in an inline-block list item horizontally

I'm working on a list with horizontal scroll functionality to allow users to view content by scrolling. I have successfully implemented this, but I'm facing a couple of challenges that I need help with: I want the first item in the list to alwa ...

Using framer-motion with Next.JS ensures that content remains consistent during navigation

I added a Link on my homepage that connects to the About Us page: <Link href="/about"><a>About us</a></Link> In my _app.js file, there is an AnimatePresence wrapper: <AnimatePresence exitBeforeEnter> <Component {...p ...

Transform an angular1 javascript circular queue implementation for calculating rolling averages into typescript

I am currently in the process of migrating a project from Angular 1 to Angular 2. One of the key components is a chart that displays a moving average line, which requires the use of a circular queue with prototype methods like add, remove, and getAverage. ...

The JavaScript jump function quickly moves back to the top of the webpage

Issue Resolved To prevent the view from jumping to the top of the page, I have implemented three options: Set the href attribute to href="#!" Set the href attribute to href="javascript:;" Pass the object to the event-handler and preve ...

Managing file system operations in Node.js

What is the most effective way to manage file access in node.js? I am currently developing an http-based uploader for exceptionally large files (10sGB) that allows for seamless resumption of uploads. I am trying to determine the optimal strategy for handl ...

What is the method for retrieving the currently selected value in a MultiColumnComboBox within Kendo for Angular?

Check out this live example created by the official Telerik team: I need to extract the id (referenced in contacts.ts) of the currently selected employee when clicking on them. How can I access this information to use in another function? ...

What causes the TypeError: 0 is not a function error when using Array.from as a callback for Array.flatMap?

An issue arises when using Array.from as a callback with Array.flatMap, resulting in the error message: "TypeError: 0 is not a function" const x = ["12"].flatMap(Array.from) console.log(x) However, when used as a regular function, Array.from operates n ...

How does the question mark symbol (?) behave when utilizing it in response? Specifically in relation to data, the API, and the fetch API

Have you encountered the curious sequence of symbols in this context? data?.name Could you explain the significance of the question mark (?) between 'data' and the period? ...

Utilizing Workbox "debug" feature with VueJS PWAs through GenerateSW

Having trouble finding consistent documentation on configurations when using GenerateSW to build your WorkBox service-worker.js? Look no further. The Workbox debug mode can help you overcome many issues in the service-worker.js: workbox.setConfig({ deb ...

Utilizing Lodash in TypeScript to merge various arrays into one cohesive array while executing computations on each individual element

I am working with a Record<string, number[][]> and attempting to perform calculations on these values. Here is an example input: const input1 = { key1: [ [2002, 10], [2003, 50], ], }; const input2 = { key ...

Utilizing Ajax to fetch a div element from a web page

Hey there! I have a link set up that loads a page into a specific div ID, which is #ey_4col3. The issue I'm facing is that it loads the entire page along with all its contents, but what I really want to load from that page is just the content within ...

Unable to capture user input text using $watch in AngularJS when applied on ng-if condition

I have developed a cross-platform application using AngularJS, Monaca, and OnsenUI. In my login view, I check if the user has previously logged in by querying a SQLite database. Depending on whether there is data in the database, I either display a welcom ...

What could be causing the failure to retrieve the salt and hash values from the database in NodeJS?

My current issue involves the retrieval of hash and salt values from the database. Although these values are being stored during sign up, they are not being retrieved when needed by the application. Below, you will find snapshots of the database, console s ...

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

The webpage is missing a rendered React component even though it should be displayed

I am facing an issue where a React component is not appearing on the webpage despite being rendered. I have provided the code and screenshots of the components below for reference. Below is the snippet from the "App.jsx" file: function createCard ...