
vue3 + element plus 实现复杂表格渲染
问题:如何使用 vue3 + element plus 的 el-table 组件实现下图所示的复杂表格?横、列都是动态的,且包含两级分类,部分单元格需要合并。
解决方案:
html 代码:
立即学习“前端免费学习笔记(深入)”;
{{ scope.row[item.prop][list.prop] }}
js 代码:
// 模拟后台返回的表格头部信息
const headerList = ref([
{
label: '达飞',
prop: 'column1',
subList: [
{
label: '保理当日',
prop: 'day'
},
{
label: '保理累计',
prop: 'total'
}
]
},
{
label: '农行',
prop: 'column2',
subList: [
{
label: '农行秦分当日',
prop: 'day'
},
{
label: '农行秦分累计',
prop: 'total'
}
]
}
])
// 模拟后台返回的表格数据信息
const tableData1 = ref([
{
group: '海港组',
total: 123,
person: 'aa',
column1: {
day: '500',
total: 3000
},
column2: { day: 100, total: 3000 }
},
{
group: '海港组',
total: 123,
person: 'bb',
column1: {
day: '500',
total: 3000
},
column2: { day: 100, total: 3000 }
},
{
group: '海港组',
total: 123,
person: 'cc',
column1: {
day: '500',
total: 3000
},
column2: { day: 100, total: 3000 }
},
{
group: '其他组',
total: 123,
person: 'cc',
column1: {
day: '500',
total: 3000
},
column2: { day: 100, total: 3000 }
},
{
group: '其他组',
total: 123,
person: 'cc',
column1: {
day: '500',
total: 3000
},
column2: { day: 100, total: 3000 }
},
{
group: '其他组',
total: 234,
person: 'cc',
column1: {
day: '500',
total: 3000
},
column2: { day: 100, total: 3000 }
}
])
const groupArr = ref([]) // 用于合并组
const groupPos = ref(0) // 合并行数默认值
const totalArr = ref([]) // 用于合并生产单
const totalPos = ref(0) // 合并生产单默认值
// 表格行合并方法
const merge = (tableData) => {
// 要合并的数组的方法
groupArr.value = []
groupPos.value = 0
totalArr.value = []
totalPos.value = 0
for (var i = 0; i < tableData.length; i++) {
if (i === 0) {
// 第一行必须存在
groupArr.value.push(1)
groupPos.value = 0
totalArr.value.push(1)
totalPos.value = 0
} else {
// 判断当前元素与上一个元素是否相同 this.groupPos是groupArr内容的序号
if (tableData[i].group === tableData[i - 1].group) {
groupArr.value[groupPos.value] += 1
groupArr.value.push(0)
} else {
groupArr.value.push(1)
groupPos.value = i
}
// 生产单合并
if (
tableData[i].total === tableData[i - 1].total &&
tableData[i].group === tableData[i - 1].group
) {
totalArr.value[totalPos.value] += 1
totalArr.value.push(0)
} else {
totalArr.value.push(1)
totalPos.value = i
}
}
}
}
// 合并行
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
if (columnIndex === 0) {
// 合并组
const _row_1 = groupArr.value[rowIndex]
const _col_1 = _row_1 > 0 ? 1 : 0 // 如果被合并了_row=0则它这个列需要取消
return {
rowspan: _row_1,
colspan: _col_1
}
} else if (columnIndex === 1) {
// 第二列的合并方法,合并生产单
const _row_2 = totalArr.value[rowIndex]
const _col_2 = _row_2 > 0 ? 1 : 0
return {
rowspan: _row_2,
colspan: _col_2
}
}
}
merge(tableData.value)说明:
- 表格头部数据的处理使用 headerlist,其中的 sublist 存储了二级分类数据。
- 表格行合并通过 arrayspanmethod 函数实现,其中 grouparr 和 totalarr 分别用于合并组和生产单。
- merge 函数用于执行数据的先预处理,根据组和生产单信息计算出合并行数和列数。
注意:
- 目前此解决方案支持前两列相同数据的合并。
- 动态列可以根据实际需求添加更多字段。










