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

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Ways to invoke Java function using Javascript (Client-side)

I have a Java Swing application that handles the User Interface, but requires JavaScript files for hardware testing. The application calls a JavaScript engine to execute functions using the `InvokeFunction()` method. Currently, I am utilizing the LabJack ...

Is it possible for me to avoid html tags inside a class without using the xmp tag?

There are a few ways to approach this question. It's important to decide which method will be most beneficial for your specific needs... Is it possible for JavaScript to recreate the deprecated <xmp> tag using an "xmp" class? Can we replicate Sta ...

The command "bin" is not identified as an internal or external command in this npm script

I'm new to using node/npm and encountering an issue when attempting to start an npm script. Every time I try to execute a simple script like the one below, I get the error message "bin is not recognized as an internal or external command." I have suc ...

The Authorization Header is added just once during an AJAX CORS request

I am making calls to my RESTful API from JavaScript in a CORS scenario. To send my POST authenticated request, I am utilizing JQuery. Below is an example: function postCall(requestSettings, includeAccessToken) { requestSettings.type = 'POST& ...

Unable to extract query parameters from URL using Express JS as req.query returns an empty object

I came across discussions about this issue here and here, but unfortunately, the solutions provided didn't work for me. I'm attempting to extract parameters from the URL using req.query. In my server.js file, I've implemented the following: ...

The function WebForm_DoCallback is not recognized

Encountering an error where WebForm_DoCallback is undefined. UPDATE WebForm_DoCallback("AccountPageControl1", "FileSave~" + fileName, CVFileSavedServerResponse, null, null, true); function CVFileSavedServerResponse(param, context) { } Why isn't ...

JasmineJS: manipulating the DOM to achieve the desired outcome

Currently, I am in the process of writing unit tests for a function that requires fetching values from the DOM for processing. getProducts: function() { //Creating query data var queryData = {}; var location = this.$('#location').val(); ...

Bug Alert: Incompatibility between Angular $resource and PHP causing issues with Update and Delete functionalities

As a newcomer to both AngularJS and PHP, I have been struggling to find comprehensive documentation on using $resource to update records in a database. While I did come across a helpful tutorial here that covers most aspects of $resource usage, I am having ...

Implement a new method called "defer" to an array that will be resolved at a later time using Promise.all()

I need to manage a queue of DB calls that will be executed only once the connection is established. The DB object is created and stored as a member of the module upon connection. DB Module: var db = { localDb: null, connectLocal: (dbName) => { ...

Using an xmlhttprequest to retrieve a PDF file functions properly in synchronous mode, but encounters issues in

Today I'm experimenting with some code that scrapes PDFs from a chrome extension by detecting user-clicked links. I've noticed that synchronous xmlhttprequests work perfectly for both HTML documents and PDFs. However, I seem to be facing an issue ...

Tips on modifying the message "Please fill out this field" in the JQuery validation plugin

Is there a way to customize the message "This field is required" in the Jquery form validation plugin to display as "このフィールドは必須です"? Changing the color of the message can be achieved using the code snippet below: <style type="tex ...

Filtering in AngularJS can be performed by checking if a value in a specific key of one array is also present as a value in a specific

This query was originally posted on this thread I am looking to implement a filter that will display the values of colors.name only if they also exist in cars.color $scope.colors = [{"name":"blue","count":2}, {"name":"red","count":12}, ...

Transfer PHP's uniqid() function to real-time using JavaScript with jQuery

Seeking a compact JavaScript(jQuery) code snippet to achieve this: date("r",hexdec(substr(uniqid(),0,8))); Your assistance is highly appreciated. Thank you. ...

Alternative image loading in a figure element

I'm currently in the process of putting together an image gallery using Angular 4.3.0, where images are displayed as background images within figure elements rather than img tags. The images are initially resized to smaller dimensions before being use ...

The position of the carousel items changes unpredictably

My jQuery carousel consists of 6 individual items scrolling horizontally. Although the scroll function is working correctly, I have noticed that 2 of the items are randomly changing their vertical position by approximately 15 pixels. Upon reviewing the HT ...

Is SWR failing to provide outdated data?

My understanding was that SWR should display the cached data upon page load before refreshing with new information from the API. However, in my Next.js app with a simple API timeout, the "loading" message appears every time due to the 5-second delay I adde ...

socket.io / settings when establishing a connection

I'm facing an issue in my node.js / Express.js app where I need to pass parameters with the socket.io connection (saw a solution in another post). On the client side, here is a snippet of my code: edit var socket = io.connect('/image/change&ap ...

The issue arises when HTML tables with unique IDs are all displaying the same value from an AJAX callback

This situation has been incredibly frustrating for me!! Let me explain what's going on - I have a callback data coming from my AJAX post method that needs to be passed to seven different HTML tables. Although I successfully received the data from the ...

AngularJS $q - pausing execution to synchronize all promises

I've encountered a challenge that I haven't been able to solve through online searches. In my project, I am using a library for selecting items and performing custom modifications through callback functions. However, I need to execute some async ...