1 demo效果
如上图实现表格中性别这一列实现行合并
2 实现要点
2.1 计算合并表格行所需数据
该方法的主要目的是在表格渲染前,为表格合并行准备合并所需的数据,示例中是通过表格中的性别来判断是否需要合并
getRowList() {
this.rowList = []
this.rowListpos = 0
this.tableData.forEach((item, index, arr) => {
if (index === 0) {
this.rowList.push(1)
this.rowListpos = 0
} else {
if (item.sex === arr[index - 1].sex) {
this.rowList[this.rowListpos] += 1
this.rowList.push(0)
} else {
this.rowList.push(1)
this.rowListpos = index
}
}
})
}
2.2 配置span-method属性
el-table中的span-method属性用来配置计算合并行或列的计算方法,该属性的回调函数有四个参数row、column、rowIndex、columnIndex,该方法需要返回一个对象,这个对象包含两个属性:rowspan和colspan两个属性,rowspan表示占用行数,colspan表示占用列数,如果两个值都为0表示不用合并
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 2) {
if (this.rowList[rowIndex]) {
const rowNum = this.rowList[rowIndex]
return {
rowspan: rowNum,
colspan: rowNum > 0 ? 1 : 0
}
} else {
return {
rowspan: 0,
colspan: 0
}
}
}
}
3 demo代码
<template>
<el-table :data&#61;"tableData" style&#61;"width: 40%" border :span-method&#61;"objectSpanMethod">
<el-table-column prop&#61;"date" label&#61;"日期" width&#61;"180">
</el-table-column>
<el-table-column prop&#61;"name" label&#61;"姓名" width&#61;"180">
</el-table-column>
<el-table-column prop&#61;"sex" label&#61;"性别" width&#61;"180">
</el-table-column>
<el-table-column prop&#61;"address" label&#61;"地址">
</el-table-column>
</el-table>
</template>
<script>
export default {
name: &#39;&#39;,
data() {
return {
rowList: [],
rowListpos: 0,
tableData: [
{
date: &#39;2016-05-02&#39;,
name: &#39;王小虎&#39;,
sex: &#39;男&#39;,
address: &#39;上海市普陀区金沙江路 1518 弄&#39;
},
{
date: &#39;2016-05-04&#39;,
name: &#39;王小虎&#39;,
sex: &#39;男&#39;,
address: &#39;上海市普陀区金沙江路 1517 弄&#39;
},
{
date: &#39;2016-05-01&#39;,
name: &#39;王小&#39;,
sex: &#39;女&#39;,
address: &#39;上海市普陀区金沙江路 1519 弄&#39;
},
{
date: &#39;2016-05-03&#39;,
name: &#39;王小&#39;,
sex: &#39;女&#39;,
address: &#39;上海市普陀区金沙江路 1516 弄&#39;
}
]
}
},
mounted() {
this.getRowList()
},
methods: {
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex &#61;&#61;&#61; 2) {
if (this.rowList[rowIndex]) {
const rowNum &#61; this.rowList[rowIndex]
return {
rowspan: rowNum,
colspan: rowNum > 0 ? 1 : 0
}
} else {
return {
rowspan: 0,
colspan: 0
}
}
}
},
getRowList() {
this.rowList &#61; []
this.rowListpos &#61; 0
this.tableData.forEach((item, index, arr) &#61;> {
if (index &#61;&#61;&#61; 0) {
this.rowList.push(1)
this.rowListpos &#61; 0
} else {
if (item.sex &#61;&#61;&#61; arr[index - 1].sex) {
this.rowList[this.rowListpos] &#43;&#61; 1
this.rowList.push(0)
} else {
this.rowList.push(1)
this.rowListpos &#61; index
}
}
})
}
}
}
</script>