1.合并第一列的所有数据,最简单的一种
html:
js:
data() {
return {
tableData: [{
id: '12987122',
name: '王小虎',
amount1: '234',
amount2: '3.2',
amount3: 10
}, {
id: '12987123',
name: '王小虎',
amount1: '165',
amount2: '4.43',
amount3: 12
}, {
id: '12987124',
name: '王小虎',
amount1: '324',
amount2: '1.9',
amount3: 9
}, {
id: '12987125',
name: '王小虎',
amount1: '621',
amount2: '2.2',
amount3: 17
}, {
id: '12987126',
name: '王小虎',
amount1: '539',
amount2: '4.1',
amount3: 15
}]
};
},
methods: {
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) { //首列 如果前面还有index 或者 selection 列可改成1或者2
if (rowIndex == 0) {
return {
rowspan:this.tableData.length, // 行合并成所有数据的长度
colspan: 1
}
} else {
return {
rowspan:0,
colspan:0
}
}
;
}else {
return {
rowspan:1,
colspan: 1
};
}
}
}
};
2.合并相同数据的列
我是借鉴大佬的代码,这里附上链接:https://www.cnblogs.com/zhang134you/p/11498762.html
这个逻辑我觉得有点复杂,有几个地方还没有弄懂,也还有其他版本,但是这个版本我动态修改数据个数的时候样式也没有乱,效果实现的最好,就先用上了
data() {
return {
tableData: [
{
id: "12987122",
name: "王小虎",
amount1: "234",
amount2: "3.2",
amount3: 10
},
{
id: "12987123",
name: "王小虎",
amount1: "234",
amount2: "4.43",
amount3: 12
},
{
id: "12987124",
name: "王小虎2",
amount1: "324",
amount2: "1.9",
amount3: 9
},
{
id: "12987125",
name: "王小虎2",
amount1: "621",
amount2: "1.9",
amount3: 17
},
{
id: "12987126",
name: "王小虎2",
amount1: "539",
amount2: "4.1",
amount3: 15
},
{
id: "12987126",
name: "王小虎5",
amount1: "539",
amount2: "4.1",
amount3: 15
}
],
pos:0,
spanArr:[],
};
},
computed:{
groupNum(){ //获取分组数据
return new Set(this.tableData.map(o => o.name));
}
},
methods: {
//table合并标签
nameGroup(name){ // 获取相同名称的数量
return this.tableData.filter(o => o.name == name).length;
},
nameLen(name){ //根据名称获取名称第一个数据在全部数据中的偏移位置
const tmp = Array.from(this.groupNum);
console.log('tmp',tmp); // ["王小虎", "王小虎2", "王小虎5"] 打印了6次,每条数据打印一次
const index = tmp.indexOf(name); //该名称在全名称中的偏移位置
console.log('index',index); // 0 0 1 1 1 2 分别对应名称的下标
let len = 0;
for (let i = 0;i < index;i++){
len += this.nameGroup(tmp[i]);
}
console.log('len1',len); // 0 0 2 2 2 5 分别对应每个名称的行数
return len;
},
objectSpanMethod(data) { //对于表格数据进行分组合并操作,UI组件回调函数
const {row,rowIndex,columnIndex} = data;
if (columnIndex == 1 ) { //名称列 合并展示区
const len = this.nameGroup(row.name);
console.log('len2' , len); // 2 2 3 3 3 1
const lenName = this.nameLen(row.name);
console.log('lenName',lenName); // 0 0 2 2 2 5
if (rowIndex === lenName) { //该名称在首位名称行
return {
rowspan:len,
colspan:1
}
} else return { //该名称不在首位名称行
rowspan: 0,
colspan: 0
};
} else { //其他列
return {
rowspan: 1,
colspan: 1
};
}
}
这两种方法在我手动添加或者删除表格数据的时候,样式都不会乱,所以大家放心大胆的用吧!
有问题欢迎指出=3=