vue绘制一个表格,列数由数据库统计数值来定,一共六行
时间: 2023-08-02 13:31:46 浏览: 65
如果列数由数据库统计数值来定,那么我们需要在获取到数据后动态生成表格的列和行。以下是一个示例代码,可以渲染出由数据库统计数值来定的表格,一共六行:
```html
<template>
<table>
<thead>
<tr>
<th v-for="(item, index) in tableHeader" :key="index">{{ item }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableHeader: [], // 表格列名
tableData: [] // 表格数据
};
},
mounted() {
// 模拟从数据库获取数据
const data = [
{ col1: 'A1', col2: 'B1', col3: 'C1', col4: 'D1' },
{ col1: 'A2', col2: 'B2', col3: 'C2', col4: 'D2', col5: 'E2' },
{ col1: 'A3', col2: 'B3', col3: 'C3', col4: 'D3', col5: 'E3', col6: 'F3' }
];
// 统计表格列名
this.tableHeader = Object.keys(data[0]);
// 统计表格数据
this.tableData = data.map(row => Object.values(row));
// 补充空行
const emptyRow = new Array(this.tableHeader.length).fill('');
while (this.tableData.length < 6) {
this.tableData.push(emptyRow);
}
}
};
</script>
```
在这个示例代码中,我们首先定义了两个空数组tableHeader和tableData,用于存储表格的列名和数据。在mounted钩子函数中,我们模拟从数据库获取数据,并根据数据动态生成表格的列和行。具体来说,我们使用Object.keys方法获取每个对象的键名,作为表格的列名;使用Object.values方法获取每个对象的值,作为表格的行数据。同时,我们使用一个while循环,补充空行,以确保表格一共有6行。最后,我们将生成的tableHeader和tableData绑定到模板中,使用v-for指令动态渲染表格的列和行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)