element ui table动态渲染表头

1.在模板中,使用 v-for 指令遍历 tableData 数组,并将每个对象的属性作为表格的列名来渲染表头。

<template>
  <el-table :data="tableData">
    <el-table-column v-for="column in tableColumns" :key="column.key" :prop="column.key" :label="column.label"></el-table-column>
  </el-table>
</template>

2.定义 tableColumns 数组,并在组件创建时根据数据动态生成它。如果想根据 tableData 中第一个对象的属性来渲染表头列,可以在 created 钩子函数中进行操作

<script>
export default {
  data() {
    return {
      tableData: [
        { id: 1, name: 'John', age: 25 },
        // 其他数据...
      ],
      tableColumns: [] // 表格列配置数组
    };
  },
  created() {
    if (this.tableData.length > 0) {
      // 获取第一个对象的属性作为表头列
      this.tableColumns = Object.keys(this.tableData[0]).map(key => {
        return { key: key, label: key };
      });
    }
  }
};
</script>

3.当 tableData 的数据发生变化时,表格的表头将会根据新的数据动态渲染。

注意:在使用动态表头时,要确保 tableData 中的每个对象都具有相同的属性结构,以保证表格正常工作。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
您可以使用 Element UI Table 组件的 `header-cell-style` 属性和 `render-header` 事件来自定义表头的样式和行为。 首先,在 Table 组件中设置 `header-cell-style` 属性来为表头单元格添加一个复选框: ```html <el-table :data="tableData" header-cell-style="{ 'background-color': '#f5f7fa' }"> <el-table-column type="selection" width="55"></el-table-column> <el-table-column label="姓名" prop="name"></el-table-column> <el-table-column label="年龄" prop="age"></el-table-column> </el-table> ``` 接下来,你需要在 `render-header` 事件中编写一个方法来监听表头的勾选事件。在该方法中,你可以获取到当前选中的列,并将其用于过滤数据: ```html <el-table :data="tableData" :header-cell-style="{ 'background-color': '#f5f7fa' }" @render-header="renderHeader"> <el-table-column type="selection" width="55"></el-table-column> <el-table-column label="姓名" prop="name"></el-table-column> <el-table-column label="年龄" prop="age"></el-table-column> </el-table> ``` ```javascript methods: { renderHeader(h, { column }) { if (column.type === 'selection') { return ( <el-checkbox indeterminate={this.isIndeterminate} nativeOn-click={this.toggleAllSelection} value={this.isAllSelected} > 全选 </el-checkbox> ) } else { return column.label } }, toggleAllSelection(event) { if (event.target.checked) { this.$refs.table.toggleAllSelection() } else { this.$refs.table.clearSelection() } this.filterTable() }, filterTable() { const selectedColumns = this.$refs.table.store.states.selection.map(item => item.age) this.filteredTableData = this.tableData.filter(item => selectedColumns.indexOf(item.age) > -1) } } ``` 在上面的代码中,我们在 Table 组件中添加了一个 `render-header` 事件,并通过 `h()` 函数来渲染表头内容。在 `toggleAllSelection()` 方法中,我们通过 `$refs` 访问 Table 组件的实例,并调用 `toggleAllSelection()` 或 `clearSelection()` 方法来切换选中状态。最后,我们在 `filterTable()` 方法中使用 `selection` 数组中的列来过滤表格数据。 这样,当用户勾选表头中的复选框时,表格数据将会自动被过滤。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值