效果图
-
优化合并表头循环(推荐) - span-method:合并行或列的计算方法
-
<template>
<div>
<!-- 表 -->
<el-table
:data="tableData"
border
ref="ref-table"
:height="tableHeight"
size="mini"
:span-method="objectSpanMethod"
>
<!-- 不合并表头 -->
<template v-for="(value, key) in tableHeader">
<el-table-column
v-if="!combineKeys.includes(key)"
align="center"
:key="key"
:prop="key"
:label="value"
>
<!-- 表头操作 -->
<template slot="header" v-if="key === 'name'">
<!-- 添加提示 -->
<el-tooltip
class="item"
effect="light"
placement="top"
>
<span
slot="content"
>
提示啦
</span>
<span>
{{value}}
<i class="el-icon-question"></i>
</span>
</el-tooltip>
</template>
</el-table-column>
</template>
<!-- 合并表头 -->
<template v-for="item in combineHeader">
<el-table-column
align="center"
:key="item.title"
:prop="item.title"
:label="item.title"
>
<el-table-column
v-for="(n) in item.column"
:key="n.field"
:prop="n.field"
:label="n.title"
align="center"
>
</el-table-column>
</el-table-column>
</template>
</el-table>
</div>
</template>
<script>
export default {
name: 'RecordPageDetail',
data() {
return {
tableHeight: 'auto', // 表高度
tableData: [
{ first_name: '韩', last_name: '信', add: '12-11', num: '小明', name: '测试', sort: '8' },
{ first_name: '韩', last_name: '信', add: '12-11', num: '小李', name: '测试', sort: '8' },
{ first_name: '韩', last_name: '信', add: '12-12', num: '小红', name: '测试', sort: '8' },
{ first_name: '韩', last_name: '信', add: '12-12', num: '小波', name: '测试', sort: '8' }
], // 表
tableHeader: {
add: '日期',
num: '审核人',
first_name: '姓',
last_name: '名',
sort: '数量1',
name: '名字'
}, // 表头
combineHeader: [{
title: '姓名',
column: [{field: 'first_name', title: '姓' }, { field: 'last_name', title: '名' }]
}, {
title: '年龄',
column: [{ field: 'sort', title: '排序' }, { field: 'name', title: '名字' }]
}], // 合并表头
combineKeys: ['first_name', 'last_name', 'name', 'sort'] // 合并的key值
};
},
methods: {
// 合并行
objectSpanMethod({ rowIndex, columnIndex }) {
const keyMap = this.formatRowspanAndColspan(this.tableData, 'add');
if (columnIndex === 0) {
return {
rowspan: keyMap[rowIndex],
colspan: 1
};
}
},
// 通过传入的key计算
formatRowspanAndColspan(tableData, key) {
const basic = [];
const computedMap = {};
tableData.forEach(t => basic.push(t[key])); // 拿到需要的这一列的所有数据
basic.forEach(t => {
computedMap[t] = computedMap[t] ? computedMap[t] + 1 : 1;
}); // 计算出每种数据需要的个数
return Object.values(computedMap).reduce((result, current) => {
return [...result, current, ...[...new Array(current - 1)].map(() => 0)];
}, []);
}
}
};
</script>
|