1、序言
源码在下方,复制粘贴就可运行
当一个表格太多列的时候,想要显示/隐藏一些列,目标效果如下:
默认情况下,展示所有列
隐藏某一列
2、原理
(1)data数据有:tableData为表格数据,columns为表头数据,checkColumns为选中的数据,checkAll为是否全选,默认情况下展示所有的数据,为columns每一行数据添加是否显示的开关,默认都为true。
(2)表格列判断是否显示的方法
(3) 判断是否全选以及刷新表格
(4)选择列:复选框@change事件参数val,返回的是一个选中的复选框的数组
(5)重置事件
(6)全选/反全选事件
3、源码
这是组件,引用并注册该组件便可使用了
export default {
name: 'App',
data() {
return {
tableData: [{
date: '2016-05-01',
name: '王小虎',
age: 13,
money: 100
}, {
date: '2016-05-02',
name: '王小虎',
age: 25,
money: 333
}, {
date: '2016-05-03',
name: '王小虎',
age: 33,
money: 555
}, {
date: '2016-05-04',
name: '王小虎',
age: 23,
money: 200
},
{
date: '2016-05-05',
name: '王小虎',
age: 26,
money: 666
}],
columns: [
{ label: '日期', prop: 'date', isShow: true },
{ label: '姓名', prop: 'name', isShow: true },
{ label: '年龄', prop: 'age', isShow: true },
{ label: '财产', prop: 'money', isShow: true },
],
checkColumns: [],
checkAll: false,
}
},
methods: {
// 全选复选框事件监听
checkAllChangeFn(val) {
if (val) {
// 全选
this.reset(true);
} else {
// 反全选
this.reset(false);
}
},
// 重置,flag: Boolean,全部重置为flag
reset(flag) {
this.columns.forEach(item => {
item.isShow = flag;
})
this.showPopover();
this.refreshTable();
},
// 表格列是否显示的方法
showColumn(currentColumn) {
return this.columns.find(item => item.prop == currentColumn).isShow;
},
/* 选择列 */
changeColumns(val) {
this.columns.forEach(item => {
item.isShow = false;
})
// columns将val数组存在的值设为true,不存在的设为false
val?.forEach(item => {
let current = this.columns.find(i => i.label == item)
current.isShow = true;
})
// 判断是否全选
this.judgeIsCheckAll();
this.refreshTable();
},
// 重新渲染表格
refreshTable() {
this.$nextTick(() => {
this.$refs.table.doLayout();
})
},
// 气泡框出现
showPopover() {
this.checkColumns = []
this.columns.forEach(item => {
if (item.isShow) {
this.checkColumns.push(item.label)
}
})
// 判断是否全选
this.judgeIsCheckAll();
},
// 判断是否全选
judgeIsCheckAll() {
// 选中的长度 = 表格列的长度 全选按钮就选中
if (this.checkColumns.length == this.columns.length)
this.checkAll = true
else
this.checkAll = false
}
}
}
/* 分割线 */
.el-divider {
margin: 10px 0;
}
/* 复选框 */
.el-checkbox-group {
display: flex;
flex-direction: column;
}
/* 操作列图标位置 */
.popover {
display: flex;
justify-content: flex-end;
font-size: 30px;
}
好文链接
发表评论