最近接了个新需求,需要用户自己筛选某一列显示与否
其实大致思路就是使用CheckBox绑定的值控制表格列绑定的v-if的值,通过vue的watch来监控CheckBox绑定值的变化来控制
下面看代码
//首先是引入element组件中的表格
<el-table :data="tableData" stripe border style="width: 98%" ref="tableDataRef">
<el-table-column type="selection" width="55" align="center"></el-table-column>
<el-table-column type="index" width="55" label="序号" align="center"></el-table-column>
<el-table-column v-if="colData[0].istrue" prop="name" label="名称" align="center"></el-table-column>
<el-table-column v-if="colData[1].istrue" prop="select" label="性别" align="center"></el-table-column>
<el-table-column v-if="colData[2].istrue" prop="kafang" label="年龄" align="center"></el-table-column>
<el-table-column v-if="colData[3].istrue" prop="fengbi" label="时间" align="center"></el-table-column>
<el-table-column v-if="colData[4].istrue" prop="isETF" label="事件" align="center"></el-table-column>
<el-table-column v-if="colData[5].istrue" prop="range" label="地点" align="center"></el-table-column>
</el-table>
//再引入CheckBox组件
<el-popover placement="right" width="400" trigger="click">
<el-checkbox-group v-model="colOptions">
<el-checkbox v-for="item in colData" :label="item.title" :key="item.title" ></el-checkbox>
</el-checkbox-group>
<el-button slot="reference">筛选列</el-button>
</el-popover>
//在data中定义上面绑定的值
/*
colData代表的是el-table-column绑定的v-if和label
colOptions代表的是多选框默认绑定的值,默认是全选,如果设置空数组的话
colSelect是筛选显示那一列的
*/
colData: [
{title: "名称",istrue: true},
{title: "性别",istrue: true},
{title: "年龄",istrue: true},
{title: "时间",istrue: true},
{title: "事件",istrue: true},
{title: "地点",istrue: true}],
colOptions: ["名称","性别", "年龄","时间","事件","地点",],
colSelect: ["名称", "性别","年龄","时间","事件", "地点",],
//在watch中监控colOptions数组的变化
colOptions(valArr) {
var arr = this.colSelect.filter(i => valArr.indexOf(i) < 0); // 将colSelect中的值筛选出来 作为未选中的
this.colData.filter(i => {
if (arr.indexOf(i.title) != -1) {
i.istrue = false;
this.$nextTick(() => {
this.$refs.tableDataRef.doLayout();
});
} else {
i.istrue = true;
this.$nextTick(() => {
this.$refs.tableDataRef.doLayout();// ref上面定义过,不懂的看一下vue官方文档
});
}
});
}
最终实现效果如下
上面的indexOf()方法请看这里点击链接
我这里有在表格中控制其他列显隐的代码 如果需要请私信