最近在使用element plus框架做一些表格,于是研究了一下如何使用该框架做复杂的表格
说先介绍一下表格合并时需要使用的一些方法
1. span-method 合并行或列的计算方法 (data: { row: any, column: any, rowIndex: number, columnIndex: number }) => number[] | { rowspan: number, colspan: number } | void
2. header-cell-style 表头单元格的 style 的回调方法,也可以使用一个固定的 Object 为所有表头单元格设置一样的 Style (data: { row: any, column: any, rowIndex: number, columnIndex: number }) => CSSProperties
3. cell-style 单元格的 style 的回调方法,也可以使用一个固定的 Object 为所有单元格设置一样的 Style (data: { row: any, column: any, rowIndex: number, columnIndex: number }) => CSSProperties
首先先写一个el-table
<el-table
:data="studentData"
height="auto"
:span-method="arraySpanMethod"
:header-cell-style="headerCellStyle"
:cell-style="cellStyle"
>
<el-table-column prop="index" label="序号" />
<el-table-column
prop="name"
label="姓名"
/>
<el-table-column prop="province" label="省" />
<el-table-column prop="city" label="市" />
<el-table-column prop="address" label="地址" />
</el-table>
效果如下
下面根据需求合并表头的省市
根据headerCellStyle方法的对象参数可知第一个是行信息,第二个是列信息,第三个是行索引,第四个是列索引
function headerCellStyle({ row, column, rowIndex, columnIndex }) {}
下面打印出需要合并表头列的信息
修改如下
function headerCellStyle({ row, column, rowIndex, columnIndex }) {
if(columnIndex == 2 ){
column.colSpan = 2
column.label = '省市'
return { backgroundColor: '#fff',
borderTop: '2px solid black',
borderBottom: '2px solid black',
borderRight: 'none',
fontSize: '2.5mm',
borderLeft: '2px solid black',
lineHeight: 'normal',
margin: 0,
padding: 0,
color: '#000',
textAlign: 'center',
}
}
if(columnIndex == 3 ){
column.colSpan = 0
return { display: 'none' }
}
return {
backgroundColor: '#fff',
borderTop: '2px solid black',
borderBottom: '2px solid black',
borderRight: '2px solid black',
fontSize: '2.5mm',
borderLeft: '2px solid black',
lineHeight: 'normal',
margin: 0,
padding: 0,
color: '#000',
textAlign: 'center',
}
}
需要注意的是表头和数据列的合并时不同的方法中
下面展示数据列的合并
span-method="arraySpanMethod"
通过给 table 传入span-method
方法可以实现合并行或列, 方法的参数是一个对象,里面包含当前行 row
、当前列 column
、当前行号 rowIndex
、当前列号 columnIndex
四个属性。 该函数可以返回一个包含两个元素的数组,第一个元素代表 rowspan
,第二个元素代表 colspan
。 也可以返回一个键名为 rowspan
和 colspan
的对象
同样合并省市的数据列
function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
if(columnIndex == 2){
return [1,2]
}
if(columnIndex == 3){
return [0,0]
}
return [1,1]
}
最终效果如下
了解更多element plus请参考官网信息