根据第二列条件合并第四列
<template>
<div>
<el-table :data="tableData" :span-method="objectSpanMethod" border style="width: 100%; margin-top: 20px">
<el-table-column prop="value1" label="机房" width="180">
</el-table-column>
<el-table-column prop="value2" label="资源分类">
</el-table-column>
<el-table-column prop="value3" label="设备类型">
</el-table-column>
<el-table-column prop="value4" label="设备总数">
</el-table-column>
</el-table>
<span>根据第二列合并最后一列</span>
</div>
</template>
<script>
export default {
name: 'DynamicTable',
data() {
return {
tableData: [{
value1: '电信广场5楼机房',
value2: 'IT设备',
value3: '服务器',
value4: '23'
}, {
value1: '电信广场5楼机房',
value2: 'IT设备',
value3: '存储设备',
value4: '24'
}, {
value1: '电信广场5楼机房',
value2: 'IT设备',
value3: '网络设备',
value4: '25'
}, {
value1: '电信广场5楼机房',
value2: '动力设备',
value3: '配电柜',
value4: '26'
}, {
value1: '电信广场5楼机房',
value2: '动力设备',
value3: 'UPS',
value4: '27'
}, {
value1: '电信广场5楼机房',
value2: '安防设备',
value3: '门禁',
value4: '28'
}, {
value1: '电信广场5楼机房',
value2: '安防设备',
value3: '摄像头',
value4: '29'
}, {
value1: '电信广场6楼机房',
value2: 'IT设备',
value3: '服务器',
value4: '23'
}, {
value1: '电信广场6楼机房',
value2: '动力设备',
value3: '配电柜',
value4: '26'
}, {
value1: '电信广场6楼机房',
value2: '动力设备',
value3: 'UPS',
value4: '27'
}, {
value1: '电信广场6楼机房',
value2: '安防设备',
value3: '门禁',
value4: '28'
}, {
value1: '电信广场7楼机房',
value2: '安防设备',
value3: '摄像头',
value4: '29'
}],
spanArr1: [], // 记录每一行的合并数
pos1: '', // 记录索引
spanArr2: [], // 记录每一行的合并数
pos2: '' // 记录索引
}
},
mounted() {
this.getSpanArr(this.tableData)
},
methods: {
// 合并行
getSpanArr(data) {
for (let i = 0; i < data.length; i++) { // 第一列
if (i === 0) {
this.spanArr1.push(1)
this.pos1 = 0
} else {
// 判断当前元素与上一个元素是否相同
if (data[i].value1 === data[i - 1].value1) {
this.spanArr1[this.pos1] += 1
this.spanArr1.push(0)
} else {
this.spanArr1.push(1)
this.pos1 = i
}
}
}
for (let i = 0; i < data.length; i++) { // 第二列
if (i === 0) {
this.spanArr2.push(1)
this.pos2 = 0
} else {
// 判断当前元素与上一个元素是否相同
if (data[i].value1 === data[i - 1].value1 && data[i].value2 === data[i - 1].value2) {
this.spanArr2[this.pos2] += 1
this.spanArr2.push(0)
} else {
this.spanArr2.push(1)
this.pos2 = i
}
}
}
},
objectSpanMethod({ rowIndex, columnIndex }) {
if (columnIndex === 0) { // 第一列
const _row = this.spanArr1[rowIndex]
const _col = _row > 0 ? 1 : 0
return {
rowspan: _row,
colspan: _col
}
}
if (columnIndex === 1) { // 第二列
const _row = this.spanArr2[rowIndex]
const _col = _row > 0 ? 1 : 0
return {
rowspan: _row,
colspan: _col
}
}
if (columnIndex === 3) { // 第二列
const _row = this.spanArr2[rowIndex]
const _col = _row > 0 ? 1 : 0
return {
rowspan: _row,
colspan: _col
}
}
}
}
}
</script>
<style scoped></style>