项目场景:含合并行列的antd-table
提示:这里简述项目相关背景:有些excel设计时会有重复的行列内容需要合并单元格,这里提供一个解决思路
解决方案:
// 表格列的配置描述
const columns = ref([
{
align: 'center',
title: '序号',
key: 'index',
},
{
align: 'center',
title: '费用指标名称',
dataIndex: 'key1',
colSpan: 3, // 表头合并占三格,如果这么设置了,下两个表头参数里需设置为0
customCell: (_, index) => {
for (let i = 0; i < dataSource.value.length; i++) {
if (index === i) {
return {
colSpan: myArray2.value[index][0], //行合并
rowSpan: myArray1.value[index], //列合并
}
}
}
},
},
{
align: 'center',
title: '值',
dataIndex: 'value',
key: 'value',
},
)]
const myArray1 = ref([])
const myArray2 = ref([])
myArray1.value = setRowSpan(dataSource.value, 'key1')
myArray2.value = setColSpan(dataSource.value)
// 列合并方法(传参为列表和对应列参数名)
function setRowSpan(data, name) {
let myArray = []
//保存上一个name
let x = ''
//相同name出现的次数
let count = 0
//该name第一次出现的位置
let startIndex= 0
for (let i = 0; i < data.length; i++) {
// console.log(data[i].groupName)
//这里是合并name列,根据各自情况大家可以自己完善
const val = data[i][name]
if (i === 0) {
x = val
count = 1
myArray[0] = 1
} else {
if (val === x) {
count++
myArray[startIndex] = count
myArray[i] = 0
} else {
count = 1
x = val
startIndex= i
myArray[i] = 1
}
}
}
return myArray
}
// 行合并方法
function setColSpan(data) {
let myArray = []
for (let i = 0; i < data.length; i++) {
const myArrayIndex = []
const content = []
let x = ''
let count = 0
let startIndex= 0
for (let key in data[i]) {
content.push(data[i][key])
} // 这里是抽离一行数据的内容
for (let j = 0; j < content.length; j++) {
const val = content[j]
if (val !== '' && val !== null) {
if (j === 0) {
x = val
count = 1
myArrayIndex[0] = 1
} else {
if (val === x) {
count++
myArrayIndex[startIndex] = count
myArrayIndex[j] = 0
} else {
count = 1
x = val
startIndex = j
myArrayIndex[j] = 1
}
}
}
}
myArray.push(myArrayIndex)
}
return myArray
}
如下图key1列需要合并,通过setRowSpan方法得到的myArray1为[3,0,0,2,0,1],即第一个值占三行,第四个值占两行,第六个值占一行,通过columns即可实现列合并

如下图行需要合并,通过setColSpan方法得到的myArray2,为[[3,0,0,2,0,1]],列表的第一行,即myArray2的第一个子列表,子列表的第一个值占三列,第四个值占两列,第六个值占一列,通过columns即可实现行合并

<a-table
bordered // 有合并行列,加上边框看着清晰一些
:dataSource="dataSource" // 源数据
:columns="columns" // 表格列的配置描述
size="small"
style="background: #1fffff00; width: 99%"
:pagination="false"
:scroll="{ y: 680 }"
>
<template #bodyCell="{ column, record, index }">
<template v-if="column.key === 'index'"> // 生成序号
{{ index + 1 }}
</template>
<template v-if="column.key === 'value'"> // 我的value列为输入框,按需设置即可
<a-input
:bordered="false"
v-model:value="record.value"
placeholder="Basic usage"
></a-input>
</template>
</template>
</a-table>
2105

被折叠的 条评论
为什么被折叠?



