[英]Using v-for with nested object in Vue
我有這種形式的數據:
itemlist : {
"dates": [
"2019-03-15",
"2019-04-01",
"2019-05-15"
],
"id": [
"arn21",
"3sa4a",
"wqa99"
],
"price": [
22,
10,
31
]
}
我想在我創建的組件中使用 v-for,該組件循環遍歷此對象,將這 3 個嵌套數組中的每個索引視為一個觀察值。 所以dates[0]
, id[0]
和price[0]
對應同一個 item,dates[1] id[1] price[1] 是第二個,依此類推。
所以換句話說,我認為我需要將其轉換為,但不確定:
0 : {
dates: "2019-03-15",
id: "arn21",
price: 22,}
1:{
dates: "2019-04-01",
id: "3sa4a",
price: 10}
}
2:...
這就是我將數據傳遞給組件的方式:
<tempc v-for="i in itemlist" :key="i.id" :price="i.price" :dates="i.dates"></temp>
但這不適用於原始數據
您可以為此創建一個計算屬性:
Vue.component('my-component', { template: '#my-component', data() { return { itemlist: { "dates": [ "2019-03-15", "2019-04-01", "2019-05-15" ], "id": [ "arn21", "3sa4a", "wqa99" ], "price": [ 22, 10, 31 ] } }; }, computed: { // Note: here I assume these arrays will always have the same length mergedList() { return this.itemlist.dates.map((dates, i) => { return { dates, id: this.itemlist.id[i], price: this.itemlist.price[i] }; }); } } }); var vm = new Vue({ el: '#app' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script> <div id="app"> <my-component></my-component> </div> <template id="my-component"> <ul> <li v-for="i in mergedList" :key="i.id" :price="i.price" :dates="i.dates"> {{i.id}} - ${{i.price}} ({{i.dates}}) </li> </ul> </template>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.