VUE ElementUI 表格多选框实现单选

需求:将 table 中的 radio 改为 checkbox 并保持同样的效果

HTML部分:

    <el-table
      :data="tableData"
      tooltip-effect="dark"
      style=" 100%"
      ref="multipleTable"
      @select-all="onSelectAll"
      @selection-change="selectItem"
      @row-click="onSelectOp">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        label="日期"
        width="120">
        <template slot-scope="scope">{{ scope.row.date }}</template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="120">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址"
        show-overflow-tooltip>
      </el-table-column>
    </el-table>

@select-all="onSelectAll"  全选事件

在点击全选的时候,把所有的选中状态清空,执行 clearSelection()

@selection-change="selectItem" 选中某一个 checkbox 事件

做判断,选中数量大于一就把上一个选中的数据勾选状态改为 false ,把新的数据勾选状态设为 true ,并赋值给 multipleSelection 数组,方便调用

@row-click="onSelectOp" 单击某行事件

单击某行,就把某行的选中状态设为 true ,在此之前执行 clearSelection()

具体代码:

    methods: {
      onSelectAll() {
        this.$refs.multipleTable.clearSelection();
      },
      selectItem(rows) {
        if (rows.length > 1) {
          var newRows = rows.filter((it, index) => {
            if (index == rows.length - 1) {
              this.$refs.multipleTable.toggleRowSelection(it, true);
              return true;
            } else {
              this.$refs.multipleTable.toggleRowSelection(it, false);
              return false;
            }
          });
          this.multipleSelection = newRows;
        } else {
          this.multipleSelection = rows;
        }
      },
      onSelectOp(row) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(row, true);
        this.multipleSelection = [];
        this.multipleSelection.push(row);
      },
    }

参考文档: http://www.manongjc.com/detail/15-kotxswczpcdsvru.html

原文地址:https://www.cnblogs.com/wyhlightstar/p/13183708.html