Skip to content

element-plus 表格跨行与跨列

vue
<script setup>
const objectSpanMethod = ({row, column, rowIndex, columnIndex}) => {
  if (columnIndex === 0) {
    if (rowIndex % 2 === 0) {
      return {
        rowspan: 2,
        colspan: 1,
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
  }

  // 0-2 开始跨列, 横跨两列,会占用 0-3 的格子
  if (rowIndex === 0 && columnIndex === 2) {
    return {rowspan: 1, colspan: 2}
  }
  // 0-3 需要消失
  if (rowIndex === 0 && columnIndex === 3) {
    return {rowspan: 0, colspan: 0}
  }

  // 2-2 开始跨行, 横跨两行,会占用 3-2 的格子
  if (rowIndex === 2 && columnIndex === 2) {
    return {rowspan: 2, colspan: 1}
  }

  //  3-2 需要消失
  if (rowIndex === 3 && columnIndex === 2) {
    return {rowspan: 2, colspan: 2}
  }

  // 3-3 跨一行一列,需要占用 3-4、4-3、4-4
  if (rowIndex === 3 && columnIndex === 3) {
    return {rowspan: 2, colspan: 2}
  }
  if (rowIndex === 3 && columnIndex === 4) {
    return {rowspan: 0, colspan: 0}
  }
  if (rowIndex === 4 && columnIndex === 3) {
    return {rowspan: 0, colspan: 0}
  }
  if (rowIndex === 4 && columnIndex === 4) {
    return {rowspan: 0, colspan: 0}
  }
}

const tableData = [
  {
    id: '0-0',
    name: '0-1',
    amount1: '0-2',
    amount2: '0-3',
    amount3: '0-4',
  },
  {
    id: '1-0',
    name: '1-1',
    amount1: '1-2',
    amount2: '1-3',
    amount3: '1-4',
  },
  {
    id: '2-0',
    name: '2-1',
    amount1: '2-2',
    amount2: '2-3',
    amount3: '2-4',
  },
  {
    id: '3-0',
    name: '3-1',
    amount1: '3-2',
    amount2: '3-3',
    amount3: '3-4',
  },
  {
    id: '4-0',
    name: '4-1',
    amount1: '4-2',
    amount2: '4-3',
    amount3: '4-4',
  },
  {
    id: '5-0',
    name: '5-1',
    amount1: '5-2',
    amount2: '5-3',
    amount3: '5-4',
  },
]
</script>

<template>
  <div>实训模式</div>

  <el-table
      :data="tableData"
      :span-method="objectSpanMethod"
      border
      style="width: 100%; margin-top: 20px"
  >
    <el-table-column prop="id" label="ID" width="180"/>
    <el-table-column prop="name" label="Name"/>
    <el-table-column prop="amount1" label="Amount 1"/>
    <el-table-column prop="amount2" label="Amount 2"/>
    <el-table-column prop="amount3" label="Amount 3"/>
  </el-table>
</template>

<style scoped>

</style>