我有一个嵌套数组,我试图在表中显示它,但是可以让我的嵌套数组显示,我的数据集看起来类似于下面。
[{ "dd": "February", "md": [ { "dag": "2020-02-01" },{ "dag": "2020-02-02" },{ "dag": "2020-02-03" }]},
{ "dd": "March", "md": [ { "dag": "2020-03-01" },{ "dag": "2020-03-02" },{ "dag": "2020-03-03" }]}]
而且我想要一张看起来像这样的桌子。
February | march |
2020-02-01 |2020-03-01|
2020-02-02 |2020-03-02|
2020-02-03 |2020-03-03|
得到了这个工作,但它给了我2张桌子而不是一张桌子
<template v-for="(md2, index) in md2s">
<table :key=index >
<thead >
<tr align="center">
<th style="width: 80px">{{md2}}</th>
</tr>
</thead>
<tr v-for="(date, index) in md2.md" :key=index>
<td align="center" >{{date.dag }}</td>
</tr>
</table>
</template>
获得所有帮助
br。埃里克
您需要进行两次不同的迭代。一个用于标题,另一个用于表主体。对于标题,您只需要在订单上添加月份名称即可。该代码段显示了如何使用计算出的属性months
。这样就完成了头的迭代。
第二个要复杂一些。您需要事先知道会有几行,为此,我创建了一个计算属性maxLength
,该属性搜索每个md
并给出较大的那一行。然后针对每个行遍历每个月,然后使用v-if
验证该月是否有足够的日期,以及是否确实从索引和嵌套数据结构中查找所需的日期。
下面的片段是一个工作示例,其中包含更复杂的数据,显示使用不同的md
大小和自动月份排序可能发生的情况。
var app = new Vue({
el: '#app',
data: () => ({
nested: [
{ "dd": "February",
"md": [{ "dag": "2020-02-01" },{ "dag": "2020-02-02" },{ "dag": "2020-02-03" },{ "dag": "2020-03-04" }]
},
{ "dd": "March",
"md": [{ "dag": "2020-03-01" },{ "dag": "2020-03-02" },{ "dag": "2020-03-03" }]
},
{ "dd": "January",
"md": [{ "dag": "2020-01-01" }]
}
]
}),
computed: {
staticMonths() {
return Array.from(Array(12),(e,i)=>new Date(25e8*++i).toLocaleString('en-US',{month: 'long'}));
},
months() {
return this.nested.map(item => item.dd).sort((a, b) => {
const A = this.staticMonths.indexOf(a);
const B = this.staticMonths.indexOf(b);
return A-B;
});
},
maxLength() {
return this.nested.reduce((accum, curr) => accum > curr.md.length ? accum : curr.md.length, 0);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<table>
<thead>
<tr>
<th v-for="(item, index) in months">{{ item }}</th>
</tr>
</thead>
<tbody>
<tr v-for="index in maxLength">
<td v-for="item in months">
<span v-if="nested.find(nest => nest.dd === item).md.length > index-1">
{{nested.find(nest=>nest.dd===item).md[index-1].dag}}
</span>
</td>
</tr>
</tbody>
</table>
</div>