Element ui Table组件动态控制列的显示隐藏
��最近遇到一个需求,要求可以动态控制 table 列表中的列的显示与隐藏,并且将选中的列进行存储,下次进入页面仍展示上次勾选的列。
经过查阅资料,实现了这个功能,创建一个Table.vue文件,组件封装代码如下:
{{scope.row[item.columnName]}} export default { props: { tableData: { type: Array, required: true, default: () => [] }, tableHead: { type: Array, required: true, default: () => [] } }, data() { return { columnSelecteds: [] // 已选择的项 } }, watch: { /* @title 监听列显示隐藏**/ columnSelecteds(newArrayVal) { // 计算为被选中的列标题数组 var nonSelecteds = this.tableHead .filter((item) => newArrayVal.indexOf(item.columnTitle) === -1) .map((item) => item.columnTitle) // 根据计算结果进行表格重绘 this.tableHead.filter((item) => { const isNonSelected = nonSelecteds.indexOf(item.columnTitle) !== -1 if (isNonSelected) { // 隐藏未选中的列 item.isShow = false this.$nextTick(() => { this.$refs.dataTable.doLayout() }) } else { // 显示已选中的列 item.isShow = true this.$nextTick(() => { this.$refs.dataTable.doLayout() }) } }) localStorage.setItem('columnSelecteds', JSON.stringify(newArrayVal)) } }, created() { // 初始化要显示的列 if (JSON.parse(localStorage.getItem('columnSelecteds')) && JSON.parse(localStorage.getItem('columnSelecteds')).length) { this.columnSelecteds = JSON.parse(localStorage.getItem('columnSelecteds')) } else { this.tableHead.forEach((item) => { if (item.isShow) { this.columnSelecteds.push(item.columnTitle) } }) localStorage.setItem('columnSelecteds', JSON.stringify(this.columnSelecteds)) } } } ::v-deep .headerCell { padding: 5px 0; background: #f5f7fa; color: #606266; } ::v-deep .contentCell { padding: 5px 0; text-align: center; } ::v-deep .el-table .cell{ white-space: nowrap; } .el-checkbox:last-of-type{ margin-right: 30px; }
组件用法如下,新建一个index.vue,将Table组件引入使用:
效果如下图:
默认只展示姓名和地址列
缓存勾选的列
可以将日期列选中,在列表中进行展示
缓存勾选的列
The End