element-ui table 组件自定义单元格合并
问题: 当后端接口返回的数据是带层级的结构,我们要怎么实现自定义的单元格合并功能呢?
// 服务端接口返回值如下
const mockData = [
{
title1: '我是title1',
children: [
{
title2: '我是title2',
children: [
{
title3: '我是title3',
title4: '我是title4',
title5: '我是title5',
title6: '我是title6'
},
{
title3: '我是title3',
title4: '我是title4',
title5: '我是title5',
title6: '我是title6'
}
]
},
{
title2: '我是title2',
children: [
{
title3: '我是title3',
title4: '我是title4',
title5: '我是title5',
title6: '我是title6'
}
]
}
]
},
{
title1: '我是title1的兄弟',
children: [
{
title2: '我是title2的兄弟',
children: [
{
title3: '我是title3的兄弟',
title4: '我是title4的兄弟',
title5: '我是title5的兄弟',
title6: '我是title6的兄弟'
},
{
title3: '我是title3的兄弟',
title4: '我是title4的兄弟',
title5: '我是title5的兄弟',
title6: '我是title6的兄弟'
}
]
},
{
title2: '我是title2',
children: [
{
title3: '我是title3',
title4: '我是title4',
title5: '我是title5',
title6: '我是title6'
}
]
}
]
}
]
这是我们想要的效果
- 首先需要将上面的数据扁平化。
methods: {
dealData() {
this.mockData.forEach(item => {
let arr = []
this.flat(item, arr)
this.dataSource = this.dataSource.concat(arr)
})
},
// 通过递归将传入的对象扁平化
flat(obj, arr) {
if(!obj.children) {
arr.push(obj)
} else {
const children = cloneDeep(obj.children)
delete obj.children
children.forEach((item) => {
this.flat({ ...obj, ...item }, arr)
})
}
},
}
- 利用table组件提供的
span-method
合并方法实现自定义合并
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if(columnIndex === 0 || columnIndex === 1) {
// 获取当前行的值
const curRowValue = row[column.property]
// 获取上一行的值
const preRow = this.dataSource[rowIndex - 1]
const preRowValue = preRow ? preRow[column.property] : null
if(preRowValue === curRowValue) {
return { rowspan: 0, colspan: 0 }
} else {
let rowspan = 1
for (let i = rowIndex + 1; i < this.dataSource.length; i ++) {
const nextRowValue = this.dataSource[i][column.property]
if(nextRowValue === curRowValue) {
rowspan ++
} else {
break
}
}
return { rowspan, colspan: 1 }
}
}
}
tip: 如果说服务端返回的结构本来就是扁平化的数据,那就可以直接使用第2步的方法实现了。