Element-plus的el-table动态列表格

时间:2025-03-04 07:38:00

Element-plus官网给出了el-table的固定列用法,适用于数据列数固顶的情况;但是有需求数据不固定,数据的列数是不确定的,这个时候就要用到动态列的el-table。(动态列这个词可能不够准确)

方法一,对某一列用slot的方式拓展,把这一列拓展成多列

<template>
  <div>
    <el-table :data="tableData">
      <el-table-column label="来源" prop="source"></el-table-column>
      <el-table-column label="目标" prop="target"></el-table-column>
      <el-table-column v-for="(item, index) in tableData[0].zbList" :key="index">
        <template #header>
          {{  }}
        </template>
        <template v-slot="{ row }">
          {{ [index].value }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name:"DynamicColumnTable",
  setup() {
    const tableData= [{
          source: '北京',
          target: '上海',
          zbList: [{
            zb: '指标一',
            value: '2000'
          },
          {
            zb: '指标二',
            value: '4000'
          },
          {
            zb: '指标三',
            value: '6000'
          },
          ]
        },
        {
          source: '北京',
          target: '天津',
          zbList: [{
          zb: '指标一',
            value: '20'
          },
          {
            zb: '指标二',
            value: '40'
          },
          {
            zb: '指标三',
            value: '60'
          },
          ]
        },
        ]
        return{
        tableData
        }   
      },
 }
</script>

方法二,根据数据来动态拓展每一列,根据数据的列数动态生成每一列

<template>
  <div>
    <el-table ref="table" :data="tableData" stripe style="width: 100%">
      <el-table-column v-for="column in columns" :key="" :prop="" :label=""
        :min-width="">
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "DynamicTable",
  setup() {
    const columns = [
      {
        prop: 'source',
        label: '来源',
        minWidth: '100px'
      },
      {
        prop: 'target',
        label: '目标',
        minWidth: '100px'
      },
      {
        prop: 'value1',
        label: 'value1(万)',
        minWidth: '150px'
      },
      {
        prop: 'value2',
        label: 'value2(亿)',
        minWidth: '150px'
      },
    ]
    const tableData = [{
      source: '北京',
      target: '上海',
      value1: '189',
      value2: '1.89'
    }, {
      source: '天津',
      target: '河北',
      value1: '233',
      value2: '2.33'
    }, {
      source: '上海',
      target: '陕西',
      value1: '97',
      value2: '0.97'
    }, {
      source: '内蒙古',
      target: '山东',
      value1: '180',
      value2: '1.80'
    }]

    return {
      columns,
      tableData
    }
  },

}
</script>