【发布时间】:2021-05-26 07:13:16
【问题描述】:
我正在构建一个 vue js 应用程序,我正在尝试用这样的数据构建一个 html 表。
{Header}:
{
{Subheader}: {
2021-05-26 00:09: [1, 2, 3]
2021-05-26 00:13: [10]
2021-05-26 00:16: [6]
{Header}
{Subheader}: {
2021-05-26 00:09: [2, 6, 1]
2021-05-26 00:13: [50]
2021-05-26 00:16: [10]
{Header}
{Subheader}: {
2021-05-26 00:09: [4]
2021-05-26 00:13: [5, 5, 8]
2021-05-26 00:16: [4]
...
现在标题和子标题可以是任何东西,这就是我将其放在括号中的原因,诀窍是显示标题,然后将其合并,以便它可以匹配其自己的子标题的长度,最后在每一行上放置相应的项目子标题值,因此根据上面的示例,它将是这样的
| Header | Header |
|Subheader|Subheader|Subheader|
| 1 | 2 | 4 |
| 2 | 6 | 5 |
| 3 | 1 | 5 |
| 10 | 50 | 8 |
| 6 | 10 | 4 |
到目前为止,这是我的 vue.js 代码
<template>
<div ref="main" class="relative h-full pt-10 analytics">
<table class="w-full" v-if="fullCycle">
<thead>
<tr>
<th class="border" :colspan="Object.values(header).length" v-for="(header, i) in fullCycle" :key="i">
{{ i }}
</th>
</tr>
<tr>
<th class="border" v-for="(item, index) in getSubValues(fullCycle)" :key="index">
{{ item }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, i) of getThirdLevel()" :key="i">
<td class="border" v-for="(val, index) in item" :key="index">{{ val }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
fullCycle: null,
};
},
mounted() {
this.init();
},
methods: {
async init() {
await this.fetchData();
},
async fetchData() {
try {
const res = await this.$axios.get('/redacted/cool-api');
this.fullCycle = res.data;
} catch (err) {
console.log(err);
}
},
getSubValues(obj) {
const values = [];
for (const item of Object.keys(obj)) {
for (const index in obj[item]) {
values.push(index);
}
}
return values;
},
getThirdLevel() {
const obj = this.fullCycle;
const levelTwoLength = this.getSubValues(obj).length;
const values = [];
for (const item of Object.keys(obj)) {
for (const index of Object.keys(obj[item])) {
values.push(Object.values(obj[item][index]));
}
}
let max = 0;
for (const item of values) {
if (max < item.length) max = item.length;
}
let iterator = 0;
let finalArray = [];
for (const item of values) {
for (let i = 0; i < max; i++) {
console.log(item[i]);
if (item[i]) {
for (let val of item[i]) {
if (!finalArray[iterator]) finalArray[iterator] = [];
finalArray[iterator].push(val ? val : '');
if (finalArray[iterator].length === levelTwoLength) iterator++;
}
} else {
if (!finalArray[iterator]) finalArray[iterator] = [];
finalArray[iterator].push('');
if (finalArray[iterator].length === levelTwoLength) iterator++;
}
}
}
return finalArray;
},
},
};
</script>
现在上面的代码有点工作,但问题是因为每天可能有很多项目,所以它把它们并排而不是从上到下。 finalArray 是一个新创建的多维数组,它是通过循环每个子标题的每个值并通过总子标题长度限制它来构建的,基本上将其推入一个新数组。同样,每个标题、子标题和日期都可以不同。每个标题可以有多个子标题
谢谢
【问题讨论】:
-
您必须计算每个子标题的子标题数量并使用最大计数作为
colspan值,然后您必须将所有子标题的 colspan 相加以获得colspan相应的标题。
标签: javascript vue.js