简体   繁体   English

如何使用v-for在html文件的一个标签中访问vue js的多个数据元素?

[英]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.这是我的 Vue 项目的一部分,我想在表格中获取一些数据元素。 I want to take data2 element like countryData in another column of the table.我想在表格的另一列中使用类似 countryData 的data2元素。 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.在 HTML 代码中,我包含了 vue js 库并简单地制作了一个表格。

 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>

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM