需求:table表格中需要把id相同的數(shù)據(jù)合并
思路: 使用 span-method 方法實現(xiàn)跨行合并,此方法的參數(shù)是一個對象,包含row 行、 column 列、rowIndex 當前行、columnIndex 當前列號;該函數(shù)會返回一個包含兩個元素的數(shù)組(第一個元素代表 rowspan,第二個元素代表 colspan),也可以是一個key為 rowspan 和 colspan 的對象。

image.png
數(shù)據(jù)格式
const tableData = [
{
id: '1',
date: new Date(),
price: '100.2',
name: "蘋果",
address: "上海市普陀區(qū)金沙江路 1518 弄",
},
{
id: '1',
date: new Date(),
price: '10.2',
name: "蘋果",
address: "上海市普陀區(qū)金沙江路 1518 弄",
},
{
id: '2',
date: new Date(),
price: '100',
name: "香蕉",
address: "上海市普陀區(qū)金沙江路 1517 弄",
},
{
id: '2',
date: new Date(),
price: '1000',
name: "香蕉2",
address: "上海市普陀區(qū)金沙江路 1517 弄",
},
{
id: '2',
date: new Date(),
price: '10',
name: "香蕉",
address: "上海市普陀區(qū)金沙江路 1517 弄",
},
{
id: '3',
date: new Date(),
price: '1300',
name: "草莓",
address: "上海市普陀區(qū)金沙江路 1519 弄",
},
{
id: '4',
date: new Date(),
price: '102130.5',
name: "哈密瓜",
address: "上海市普陀區(qū)金沙江路 1516 弄",
},
{
id: '4',
date: new Date(),
price: '102130.5',
name: "哈密瓜",
address: "上海市普陀區(qū)金沙江路 1516 弄",
},
{
id: '4',
date: new Date(),
price: '102130.5',
name: "哈密瓜",
address: "上海市普陀區(qū)金沙江路 1516 弄",
},
{
id: '4',
date: new Date(),
price: '102130.5',
name: "哈密瓜",
address: "上海市普陀區(qū)金沙江路 1516 弄",
},
]
export default tableData
1.使用計算屬性對哪行需要合并進行處理
computed: {
tableDataColumn() {
const obj = {};
this.tableData.forEach((v, i) => {
const id = v.id;
if (obj[id]) {
obj[id].push(i);
} else {
obj[id] = [];
obj[id].push(i);
}
});
return obj;
},
},
2.實現(xiàn)方法
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
if (rowIndex > 0 && row.id === this.tableData[rowIndex - 1].id) {
return {
rowspan: 0,
colspan: 0,
};
} else {
const id = row.id;
const rows = this.tableDataColumn[id];
const length = rows.length;
return {
rowspan: length,
colspan: 1,
};
}
}
},