摘要:为了自己以后用起来方便,还是记录一下
<el-table :data="tableData" :span-method="objectSpanMethod" border style=" 100%; margin-top: 20px"> <el-table-column prop="id" label="ID" width="180"> </el-table-column> <el-table-column prop="name" label="姓名"> </el-table-column> <el-table-column prop="amount1" label="数值 1(元)"> </el-table-column> <el-table-column prop="amount2" label="数值 2(元)"> </el-table-column> <el-table-column prop="amount3" label="数值 3(元)"> </el-table-column> </el-table>
export default { data() { return { tableData: [{ id: '张三', name: '王小虎', amount1: '234', amount2: '3.2', amount3: 10 }, { id: '李四', name: '王小虎', amount1: '621', amount2: '2.2', amount3: 17 },{ id: '张三', name: '王小虎', amount1: '621', amount2: '2.2', amount3: 17 },{ id: '李四', name: '王小虎', amount1: '165', amount2: '4.43', amount3: 12 }, { id: '张三', name: '王小虎', amount1: '324', amount2: '1.9', amount3: 9 }, { id: '张三', name: '王小虎', amount1: '539', amount2: '4.1', amount3: 15 }], orgTypeIndexArr:[] }; }, created() { this.conductData() }, methods: { // 数组排序 将相同id的项整合在一起 conductData() { let cache = {}; //存储的是键是id 的值,值是id 在indeces中数组的下标 let indices = []; //数组中每一个值是一个数组,数组中的每一个元素是原数组中相同id的下标 (二维数组[[], []]) this.tableData.map((item,index)=>{ let id = item.id; let idx = cache[id]; //indices中对应的下标 if (idx!==undefined){ //判断是否未定义(cache对象中未定义时 如cache['zhangsan'] === 'undefined' 注:此处必须是全等 例:0==undefined) indices[idx].push(index) // 将原数组中id的下标赋给indices对应下标的数组 例:[[0、2、4、5]]id为张三的下标集合 } else { cache[id] = indices.length //将indices的长度赋给cache[zhangsan或lisi] indices.push([index]) //记录下标 此处运行的次数与不同id的个数相等 } }) console.log(indices) // [[0、2、4、5], [1,3]] 分别对应id为张三、李四的原数组中id下标的集合 //以下是通过indices中记录的下标 整合原数组 (简单就不描述了 嘿嘿!) let result = []; indices.map((item)=>{ item.map((index)=>{ result.push(this.tableData[index]) }) }) this.tableData = result }, //合并单元格 getTableData() { let spanOneArr = [], spanTwoArr = [], concatOne = 0, concatTwo = 0; this.tableData.forEach((item, index) => { if (index === 0) { spanOneArr.push(1); spanTwoArr.push(1); } else { if (item.id === this.tableData[index - 1].id) { //第一列需合并相同内容的判断条件 spanOneArr[concatOne] += 1; spanOneArr.push(0); } else { spanOneArr.push(1); concatOne = index; } } }); return { one: spanOneArr, two: spanTwoArr }; }, objectSpanMethod({ row, column, rowIndex, columnIndex }) { if (columnIndex === 0) { const _row = this.getTableData().one[rowIndex]; const _col = _row > 0 ? 1 : 0; return { rowspan: _row, colspan: _col }; } }, } };