效果如下:
el-table中,只要将表格data绑定数据的键,与el-table-column的prop对应上,就可正常渲染。如在正常表格中, tableData 中的address: "上海市普陀区金沙江路 1519 弄"
,与prop: "address"
可对应上即可渲染出数据
为了将表格横过来,我们将原来的 列数据 转换为 行数据
// 列数据
const tableData = [
{
date: "2016-05-02",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
},
{
date: "2016-05-04",
name: "王小虎",
address: "上海市普陀区金沙江路 1517 弄",
},
{
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
},
{
date: "2016-05-03",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
];
// 行数据
const DemoTableData = [
{
"title": "日期",
"value0": "2016-05-02",
"value1": "2016-05-04",
"value2": "2016-05-01",
"value3": "2016-05-03"
},
{
"title": "姓名",
"value0": "王小虎",
"value1": "王小虎",
"value2": "王小虎",
"value3": "王小虎"
},
{
"title": "地址",
"value0": "上海市普陀区金沙江路 1518 弄",
"value1": "上海市普陀区金沙江路 1517 弄",
"value2": "上海市普陀区金沙江路 1519 弄",
"value3": "上海市普陀区金沙江路 1516 弄"
}
]
也就是说,之前的表头也将作为数据
<el-table
style="width: 100%"
:data="getValues"
>
<el-table-column
v-for="(item, index) in getHeaders"
:key="index"
:prop="item"
:show-header="false"
>
</el-table-column>
</el-table>
完整代码:
<template>
<div class="element-main">
<div>Element-ui 官方提供 table Demo</div>
<el-table style="width: 100%" :data="tableData">
<el-table-column prop="date" label="日期" width="180"> </el-table-column>
<el-table-column prop="name" label="姓名" width="180"> </el-table-column>
<el-table-column prop="address" label="地址"> </el-table-column>
</el-table>
<div>
===================================== 分割线
=====================================
</div>
<div>行列转换后的 Demo</div>
<el-table style="width: 100%" :data="DemoTableData" :show-header="false">
<el-table-column
v-for="(item, index) in DemoTableHeader"
:key="index"
:prop="item"
>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
name: "APP",
setup() {
const headers = [
{
prop: "date",
label: "日期",
},
{
prop: "name",
label: "姓名",
},
{
prop: "address",
label: "地址",
},
];
const tableData = [
{
date: "2016-05-02",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
},
{
date: "2016-05-04",
name: "王小虎",
address: "上海市普陀区金沙江路 1517 弄",
},
{
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
},
{
date: "2016-05-03",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
];
const DemoTableHeader = getHeaders();
const DemoTableData = getValues();
function getHeaders() {
return tableData.reduce(
(pre, cur, index) => pre.concat(`value${index}`),
["title"]
);
}
function getValues() {
return headers.map((item) => {
return tableData.reduce(
(pre, cur, index) =>
Object.assign(pre, { ["value" + index]: cur[item.prop] }),
{ title: item.label }
);
});
}
return {
headers,
tableData,
getHeaders,
getValues,
DemoTableHeader,
DemoTableData,
};
},
};
</script>