el-table列相同数据合并行
1、效果
2、数据
[ { "date":"2016-05-02", "name":"王小虎", "address":"上海市普陀区金沙江路 1518 弄" }, { "date":"2016-05-04", "name":"王小虎", "address":"上海市普陀区金沙江路 1517 弄" }, { "date":"2016-05-01", "name":"王小虎", "address":"上海市普陀区金沙江路 1519 弄" }, { "date":"2016-05-03", "name":"王小虎", "address":"上海市普陀区金沙江路 1516 弄" } ]
3、代码
<template> <div> <el-table class="m-table m-t-20" :data="list" :span-method="objectSpanMethod" style="width: 100%" border center> <el-table-column prop="date" label="日期" width="90"></el-table-column> <el-table-column prop="name" label="名称" width="180"></el-table-column> <el-table-column prop="address" label="地址" width="200"></el-table-column> </el-table> </div> </template> <script> export default { data() { return { spanArr: [],//用于存放每一行记录的合并数 list: [{ date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' }, { date: '2016-05-04', name: '王小虎', address: '上海市普陀区金沙江路 1517 弄' }, { date: '2016-05-01', name: '王小虎', address: '上海市普陀区金沙江路 1519 弄' }, { date: '2016-05-03', name: '王小虎', address: '上海市普陀区金沙江路 1516 弄' }], } }, created() { this.getSpanArr(this.list) }, methods: { getSpanArr(data) { this.pos = 0 for (let i = 0; i < data.length; i++) { if (i === 0) { // 如果是第一条记录(即索引是0的时候),向数组中加入1 this.spanArr.push(1) this.pos = 0 } else { if (data[i].name === data[i-1].name) { // 如果name相等就累加,并且push 0 (这里的判断视自己的判定依据改变) this.spanArr[this.pos] += 1 this.spanArr.push(0) } else { // 不相等push 1 this.spanArr.push(1) this.pos = i } } } }, objectSpanMethod({row, column, rowIndex, columnIndex}) { // 用于设置要合并的列 0 表示第一列 // 名称 跨行显示 if ([1].includes(columnIndex)) { const cRow = this.spanArr[rowIndex] const cCol = cRow > 0 ? 1 : 0 return { rowspan: cRow, // 合并的行数 colspan: cCol // 合并的列数,为0表示不显示 } } } }, } </script>