前言
正常情况下,表格的表头每一项都会显示,但在一些特殊场景下,用户需要动态的控制
表头的显隐,本篇文章主要就是为大家详细讲解了了如何动态的控制表头的显隐,感兴
趣的小伙伴可以参考一下。
如何实现?
本章节用的组件
- Popover 弹出框
- Checkbox 多选框
- Button 按钮
- Table 表格
实现思路
1.首先,我们需要用到多选框组去绑定表头的值,通过 reference 触发 Popover 显示的 HTML 元素;
2.其次,通过 v-if="数组[下标].状态" 给表格的每一列绑定上动态的状态,以此判断表格的每一列是否显隐;
3.最后,当我们勾选或者取消勾选选框时,通过 filter 方法对数组进行过滤,再利用 indexOf 方法的特性让其每一列的状态更新(true 或者 false)即可。
话不多说,下面直接看实例代码
<template>
<div class="containerBox">
<!-- Popover 弹出框 -->
<div class="tabControlBox">
<el-popover placement="right" trigger="click">
<el-checkbox-group v-model="colOptions">
<el-checkbox v-for="item in colSelect" :label="item" :key="item" @change="columnChange"></el-checkbox>
</el-checkbox-group>
<!-- reference 触发 Popover 显示的 HTML 元素 -->
<el-button icon="el-icon-menu" type="info" size="mini" slot="reference">显示列</el-button>
</el-popover>
</div>
<!-- Table 表格 -->
<div class="tableBox">
<el-table :data="tableData" border>
<el-table-column label="姓名" v-if="colData[0].ishide" prop="name"></el-table-column>
<el-table-column label="性别" v-if="colData[1].ishide" prop="sex"></el-table-column>
<el-table-column label="年龄" v-if="colData[2].ishide" prop="age"></el-table-column>
<el-table-column label="电话" v-if="colData[3].ishide" prop="phone"></el-table-column>
<el-table-column label="邮箱" v-if="colData[4].ishide" prop="email"></el-table-column>
<el-table-column label="学历" v-if="colData[5].ishide" prop="education"></el-table-column>
<el-table-column label="职业" v-if="colData[6].ishide" prop="occupation"></el-table-column>
<el-table-column label="地址" v-if="colData[7].ishide" prop="site"></el-table-column>
</el-table>
</div>
</div>
</template>
<script>
export default {
data() {
return {
// 模拟表格数据
tableData: [
{
name: "小红",
sex: "女",
age: "20",
phone: "177****8810",
email: "2901626033@qq.com",
education: "本科",
occupation: "前端开发",
site: "北京昌平",
},
],
//动态显示列
colData: [
{ title: "姓名", ishide: true },
{ title: "性别", ishide: true },
{ title: "年龄", ishide: true },
{ title: "电话", ishide: true },
{ title: "邮箱", ishide: false },
{ title: "学历", ishide: true },
{ title: "职业", ishide: false },
{ title: "地址", ishide: true },
],
// 多选框绑定值
colOptions: ["姓名", "性别", "年龄", "电话", "学历", "地址"],
// 多选框展示的值
colSelect: ["姓名","性别","年龄","电话","邮箱","学历","职业","地址"],
};
},
methods: {
//动态显示列
columnChange() {
this.colData.filter((i) => {
if (this.colOptions.indexOf(i.title) !== -1) {
i.ishide = true;
} else {
i.ishide = false;
}
});
},
},
};
</script>
<style scoped>
.containerBox {
padding: 20px;
}
.tabControlBox {
margin-bottom: 10px;
}
</style>
实现效果