ElementUI Table 表格动态添加行和列
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                在ElementUI的Table组件中,可以通过更新表格绑定的数据来动态添加行和列。以下是一个简单的例子,展示了如何动态添加行和列:
<template>
  <el-button @click="addRow">添加行</el-button>
  <el-button @click="addColumn">添加列</el-button>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="date" label="日期" width="180"></el-table-column>
    <el-table-column v-for="col in columns" :key="col.prop" :prop="col.prop" :label="col.label"></el-table-column>
  </el-table>
</template>
 
<script>
export default {
  data() {
    return {
      tableData: [
        { date: '2016-05-02', name: 'Tom', address: 'No.189, Grove St, Los Angeles' }
      ],
      columns: [
        { label: '姓名', prop: 'name' },
        { label: '地址', prop: 'address' }
      ]
    };
  },
  methods: {
    addRow() {
      const newRow = { date: 'New Date', name: 'New Name', address: 'New Address' };
      this.tableData.push(newRow);
    },
    addColumn() {
      const newColumn = { label: `Column ${this.columns.length + 1}`, prop: `col${this.columns.length + 1}` };
      this.columns.push(newColumn);
      // 更新tableData以包含新列
      this.tableData = this.tableData.map(row => ({ ...row, [newColumn.prop]: `Data for ${newColumn.prop}` }));
    }
  }
};
</script>在这个例子中,addRow方法用于向tableData数组添加新的行,而addColumn方法用于向columns数组添加新的列,并更新tableData以包含新的列数据。ElementUI的Table组件会响应数据的变化自动更新UI。
评论已关闭