element 控制表格列显隐

最近接了个新需求,需要用户自己筛选某一列显示与否

其实大致思路就是使用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()方法请看这里点击链接

我这里有在表格中控制其他列显隐的代码 如果需要请私信

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值