vue:遇到的坑之-----动态控制表格列的显隐(element-ui)

效果如图:

表格内容啥的就不要管了,专注于效果哈~

 

vue:遇到的坑之-----动态控制表格列的显隐(element-ui)_第1张图片

html: 我是通过v-if="colData[0].istrue",通过勾选框的选中和不选中来控制对应列的istrue的true/false,从而控制每一列的显隐。


      
      
      
      
      
      
      
      
 



    
        
    
    设置

 

data:colData是所有表头标题,colOptions是多选框默认全选,colSelect也是所有表头标题,只是是跟多选框组绑定的

colData: [{title: "名称",istrue: true},
          {title: "性别",istrue: true},
          {title: "年龄",istrue: true},
          {title: "时间",istrue: true},
          {title: "事件",istrue: true},
          {title: "地点",istrue: true}],
colOptions: ["名称","性别", "年龄","时间","事件","地点",], //默认全选
colSelect: ["名称", "性别","年龄","时间","事件", "地点",]

js:我是直接放在watch里监听选中的选项,代码写的很清楚,我就不解释了

watch: {
    colOptions(valArr) {
      var arr = this.colSelect.filter(i => valArr.indexOf(i) < 0); // 未选中
      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();
          });
        }
      });
    }
  }

然后就没啦,是不是看着很简单0.0,但是用的时候比较麻烦。。因为要一行一行的贴代码balbala的。

参考了好多大神的回答,终于琢磨出来了,虽然有点复杂,代码看着也有冗余。。。但是能做出来我就很满足了_(:з」∠)_ ,等我手头的内容都弄完了有时间的话我再研究下怎么优化代码。。。(虽然不太可能( ・´ω`・ ))

 

我的方法不一定是最简洁的,但是也是可以拿来应急的~仅供参考哈,如果有可以优化的地方请告诉我哈!

 

--------------------------------------

时隔三个月。。优化了代码,旧代码就不删了,做个对比

html部分不变

data部分:

colData: [{title: "名称",istrue: true},
          {title: "性别",istrue: true},
          {title: "年龄",istrue: true},
          {title: "时间",istrue: true},
          {title: "事件",istrue: true},
          {title: "地点",istrue: true}],
colOptions: [],
colSelect: []

js部分:增加了created里的代码,watch方法不变

created() {
  var _this = this;
  for (let i = 0; i < _this.colData.length; i++) {
     _this.colSelect.push(_this.colData[i].title);
    if (_this.colData[i].title == '名称') { //初始化不想展示的列可以放在这个条件里
      continue;
     }
     _this.colOptions.push(_this.colData[i].title); 
      
  }
},
watch: {
  colOptions(valArr) {
    var arr = this.colSelect.filter(i => valArr.indexOf(i) < 0); // 未选中
    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();
        });
      }
    });
  }
}

然后评论说换成下拉列表该怎么弄,其实是一样的道理~就把popover改成多选下拉框就好啦,其他地方不需要改动,效果如下:


  
  

vue:遇到的坑之-----动态控制表格列的显隐(element-ui)_第2张图片

over!后面如果有其他功能再继续优化~

你可能感兴趣的:(填坑,element-ui,vue,动态控制列显隐)