element-ui表格组件table实现列的动态显示与隐藏
<el-table :data="tableData"> <block v-for="item in bindTableColumns1"> <template v-if="item.prop == 'date'"> <el-table-column :prop="item.prop" :label="item.label" :key="item.prop"> <template slot-scope="scope"> {{ scope.row.date }}日期 </template> </el-table-column> </template> <template v-else> <el-table-column :prop="item.prop" :label="item.label" :key="item.prop"></el-table-column> </template> </block> </el-table> <label>请选择表格需要展示的列:{{ checkedTableColumns }}</label> <el-checkbox-group v-model="checkedTableColumns"> <el-checkbox v-for="column in tableColumns" :key="column.prop" :label="column.prop">{{ column.label }}</el-checkbox> </el-checkbox-group>
export default { data() { return { tableColumns: [ { prop: "date", label: "日期", show: true }, { prop: "name", label: "姓名", show: true }, { prop: "address", label: "地址", show: false }, ], tableData: [ { date: "2016-05-02", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄", }, { date: "2016-05-04", name: "王小虎", address: "上海市普陀区金沙江路 1517 弄", }, { date: "2016-05-01", name: "王小虎", address: "上海市普陀区金沙江路 1519 弄", } ], } }, computed: { bindTableColumns() { return this.tableColumns.filter((column) => column.show); }, bindTableColumns1: { get() { return this.tableColumns.filter((column) => column.show); }, set(value) { } }, /* 这里使用了getter和setter,这样写的好处是不用自己手动监听复选框的选中事件 */ checkedTableColumns: { get() { // 返回选中的列名 return this.bindTableColumns.map(column => column.prop); }, set(checked) { // 设置表格列的显示与隐藏 this.tableColumns.forEach(column => { // 如果选中,则设置列显示 if (checked.includes(column.prop)) { column.show = true; } else { // 如果未选中,则设置列隐藏 column.show = false; } }) } } },