vue+element-ui实现表格checkbox单选

 公司平台利用vue+elementui搭建前端页面,因为本人第一次使用vue也遇到了不少坑,因为我要实现的效果如下图所示

实现这种单选框,只能选择一个,但element-ui展示的是多选框,checkbox自己也可以写,但不想写,还是想用element-ui实现表格单选,于是就用了element-ui中的方法实现了,贴代码:

methods: {
    select (selection, row) {
      console.log(selection.length);
      console.log(
        Object.prototype.toString.call(selection[0]) === '[object Object]' 
      );
      this.$refs.multipleTable.clearSelection();
      if (selection.length === 0) { // 判断selection是否有值存在
        return;
      };
      console.log('点击', selection, row);
      this.$refs.multipleTable.toggleRowSelection(row, true);
    }
}

  其中select对应的事件名是table的select事件,我利用selection参数判断参数是否选中,selection选中 (2) [{…}, {…}, __ob__: Observer] ,未选中是: [ __ob__: Observer] ,__ob__: Observer是observe 工厂函数 也是实现数据响应式, 本来想用Object.prototype.toString.call(selection[0]) === '[object Object]' 这个判断的,因本人粗心,将'[object Object]'写成了'[Object Object]'导致判断不对,最后改成了数组的长度判断,正常selection选中 (2) [{…}, {…}, __ob__: Observer] 里面应该有一个对象的,因为单选,没有将上个对象清除所以导致现在选中有两个对象,但是没有关系,因为我们用row, table在选择是会触发select事件,先将this.$refs.multipleTable.clearSelection();清除掉表格的选中状态,后面开始判断若没有选中checkbox则return,否则利用row,this.$refs.multipleTable.toggleRowSelection(row, true);选中当前行,我在做的时候让表格默认选中第一行;代码如下:

 1 methods: {
 2    getManage (data = {}) { // 获取列表
 3       this.$nextTick(() => {
 4         manageList(data).then(res => {
 5           this.manageList = res.storages || [];
 6           console.log(this.manageList);
 7           if (this.manageList.length === 0) { return; };
 8           setTimeout(() => {
 9             this.$refs.multipleTable.toggleRowSelection(this.manageList[0], true);11           }, 0);
12         });
13       });
14 },
15 mounted () {
16     this.getManage();
17   },
manageList(data)是我封装的请求列表的函数,所以这个不用管,this.manageList = res.storages || [];这个是判断我是否请求到数据,if (this.manageList.length === 0) { return; }; 如果没有数据表格就是空的,返回,其实这两步我主要是针对搜索的,因为搜索不对会没有数据,最主要的就是下面一步
setTimeout(() => {this.$refs.multipleTable.toggleRowSelection(this.manageList[0], true);}, 0); 如果有数据的情况下,就获取表格的第一行数据,就可以默认选中第一行,如果不使用settimeout是不会选中的,因为vue是异步更新,我的理解是因为vue是异步更新,不添加setTimeout,我们里面的代码是同步的,在数据变化,dom更新之前默认选中第一行已经执行,但dom还没有更新
渲染,等到$nextTick完成页面更新渲染,我们的选中行代码已经执行完毕,加上settimeout同样是异步操作,同时也能获取到dom数据变化之后dom更新,对于更深的还有待研究

猜你喜欢

转载自www.cnblogs.com/dwenz/p/10142272.html