Lakshay Khandelwal
Lakshay Khandelwal

Reputation: 81

How to access multiple data elements of vue js in one tag of html file using v-for?

This is a part of my Vue project where I want to get some data elements in a table. I want to take data2 element like countryData in another column of the table. How can I do this? You can run the snippet for further reference.

In HTML code I have included the vue js library and simply made a table.

var app = new Vue({
  el: "#app",
  data(){
    return {
    countryData:[{name:"india", "1999":9537, "2000":10874},
                 {name:"china", "1999":7537, "2000":8874},
                 {name:"england", "1999":11537, "2000":12074}
                 ],
        data2: [
       {ser1: 1, ser2: 7},
       {ser1: 4, ser2: 1},
       {ser1: 6, ser2: 8}
    ]}
    }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

<div>
<h3>Data Table</h3>
</div>
<table>
<thead>
<tr>
<th>Country</th>
<th>Sales</th>
</tr>
</thead>
<tbody>
<tr v-for="x in countryData">
<td>{{x.name}}</td>
<! -- I want to take data2 element in another column of my table -->
</tr>

</tbody>
</table>

</div>

Upvotes: 1

Views: 275

Answers (1)

AVJT82
AVJT82

Reputation: 73337

You can either combine the data as you wish, before displaying in template, for example:

countryData: [
  { name: "india", "1999": 9537, "2000": 10874 },
  { name: "china", "1999": 7537, "2000": 8874 },
  { name: "england", "1999": 11537, "2000": 12074 }
],
data2: [{ ser1: 1, ser2: 7 }, { ser1: 4, ser2: 1 }, { ser1: 6, ser2: 8 }],
combinedData: []

// ...

created() {
  this.countryData.forEach((x, i) => {
    this.combinedData.push({ ...x, ...this.data2[i] });
  });
}

Then you can access in template with:

<tr v-for="(x, i) in combinedData" :key="i">
  <td>{{x.name}}</td>
  <td>{{x.ser1}}</td>
  <td>{{x.ser2}}</td>
</tr>

or you can utilize the index in the template:

<tr v-for="(x, i) in countryData" :key="i">
  <td>{{x.name}}</td>
  <td>{{data2[i].ser1}}</td>
  <td>{{data2[i].ser2}}</td>
</tr>

Upvotes: 1

Related Questions