Element Plus v2.4.0, repl v3.4.0
<template>
<div>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="name" label="名字" width="180" />
<el-table-column prop="weight" label="重量" width="180" />
<el-table-column prop="maxWeight" label="最大重量" width="180" />
<el-table-column prop="height" label="高度" width="180" />
<el-table-column prop="width" label="宽度" width="180" />
<el-table-column prop="speed" label="速度" width="180" />
</el-table>
<!-- 转置代码 -->
<div>转置table</div>
<el-table :data="trans_tableData" style="width:100%">
<el-table-column
prop="title"
label="">
</el-table-column>
<el-table-column
v-for="(item,index) in props"
:key="index"
:prop="item.value"
:label="item.label">
<template v-slot:header>
<span v-html="item.label"></span>
</template>
<template v-slot="{ row }">
<span>{{ row[item.value] }}</span>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script lang="ts" setup>
let tableData = [
{
name: '歼-20',
weight: '25吨',
maxWeight: '37吨',
height: '4.69米',
width: '21.2米',
speed: '2马赫'
},
{
name: '歼-20-1',
weight: '25吨-1',
maxWeight: '37吨-1',
height: '4.69米-1',
width: '21.2米-1',
speed: '2马赫-1'
}
]
const props = tableData.map((t) => {
return {
label: t.name,
value: t.id || t.name
}
})
console.log("props=",props)
function isExist (newArr, name) {
for (let i = 0; i < newArr.length; i++) {
if (newArr[i].title === name) {
return newArr[i]
}
}
return false
}
/**
* 定义映射字段表(最好取全量字段)
* */
const mapObj = {
name: '名称',
weight: '重量',
maxWeight: '最大载重',
height: '高度',
width: '宽度',
speed: '速度'
}
const newArr = []
for (const t in mapObj) {
for (let i = 0; i < tableData.length; i++) {
const item = tableData[i]
const result = isExist(newArr, mapObj[t])
if (result) {
result[item.name] = item[t] || ''
} else {
const obj = {}
obj.title = mapObj[t]
obj[item.name] = item[t] || ''
newArr.push(obj)
}
}
}
console.log("newArr",newArr)
const trans_tableData = newArr
</script>