有些业务需求是需要table进行行合并的,所以就写了个通用的方法来处理,废话不多说,先上图
首先是内部使用el-table的方法:span-method='objectSpanMethod'
data() {
return {
table: [{
id: '1',
checkRoom: 'CTROOM',
checkProject: '颈椎MRICT',
checkMoney: '300.22',
attention: '检查前空腹',
appointmentTime: ''
},{
id: '1',
checkRoom: 'CTROOM',
checkProject: '颈椎MRICT1',
checkMoney: '303.22',
attention: '检查前空腹',
appointmentTime: ''
},{
id: '1',
checkRoom: 'CTROOM',
checkProject: '颈椎MRICT22',
checkMoney: '340.22',
attention: '检查前空腹',
appointmentTime: '2019-5-29 10:30'
},{
id: '1',
checkRoom: 'DR',
checkProject: '鼻骨',
checkMoney: '340.22',
attention: '检查前空腹',
appointmentTime: '2019-5-29 9:30'
}]
};
},
created(){
// 给table赋值,重新遍历新增rowSpan属性,checkRoom,appointmentTime为table里面需要合并的属性名称
this.table = this.mergeTableRow({
data: this.table,
mergeColNames: ['checkRoom', 'checkMoney', 'attention', 'appointmentTime'], // 需要合并的列,默认合并列相同的数据
firstMergeColNames: ['attention'], // 受影响的列,只合并以firstMerge为首的同类型数据
firstMerge: 'checkRoom' // 以哪列为基础进行合并,一般为第一列
})
// 例如:如果firstMerge: 'checkRoom'合并了三行,受影响的列也应该是最多合并三行,请看下图1
// 例如:如果firstMerge: 'checkMoney'合并了两行,受影响的列也应该是最多合并两行,请看下图2
},
methods: {
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
const span = column['property'] + '-span'
if(row[span]){
return row[span]
}
}
}
图一 ⬆
图二 ⬆
通用合并的方法mergeTableRow,请看最下面那个方法二
⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇由于好多人都不看全文章,方法一已经废弃⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇
如果相同的数据不在相邻行该怎么办呢?那么请看下面的代码,改良过后的,不相邻的数据相互之间不受影响
/**
* 方法二
* 改良后(不相邻的数据相互不受影响)
* table合并行通用 */
export function mergeTableRow(config) {
let data = config.data
const { mergeColNames, firstMergeColNames, firstMerge } = config
if (!mergeColNames || mergeColNames.length === 0) {
return data
}
mergeColNames.forEach((m) => {
const mList = {}
data = data.map((v, index) => {
const rowVal = v[m]
if (mList[rowVal] && mList[rowVal].newIndex === index) {
const flag = firstMergeColNames.filter((f) => { return f === m }).length !== 0
const mcFlag = mergeColNames.filter((mc) => { return mc === firstMerge }).length === 0
if ((mcFlag && flag) || (flag && data[index][firstMerge + '-span'] && data[index][firstMerge + '-span'].rowspan === 1)) {
v[m + '-span'] = {
rowspan: 1,
colspan: 1
}
} else {
data[mList[rowVal]['index']][m + '-span'].rowspan++
v[m + '-span'] = {
rowspan: 0,
colspan: 0
}
mList[rowVal]['num']++
mList[rowVal]['newIndex']++
}
} else {
mList[rowVal] = { num: 1, index: index, newIndex: index + 1 }
v[m + '-span'] = {
rowspan: 1,
colspan: 1
}
}
return v
})
})
return data
}
注:由于数据没有进行排序,所以要求后端返回的数据需要相同的在一块,要不会出现行错乱现象