el-table使用 span-method 合并某個字段相同的單元格

需求: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,
          };
        }
      }
    },
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容