天天看点

vue elementUI实现el-table点击行单选, 点击行多选,点击复选框单选效果

❤️ 以下分别介绍这四种效果的实现方式,非常简单!

首先:table绑定点击行事件 @row-click="rowClick"

           绑定复选框勾选事件 @select="handleSelectionChange"

 <el-table
        ref="Table"
        :data="tableData"
        style="width: 100%"
        :select-on-indeterminate="false"
        @select="handleSelectionChange"
        @row-click="rowClick"
      >
    //......
           
1、点击行多选
rowClick(row, column, event) {  // 点击行多选
        // console.log(row)
        // 从已选中数据中 判断当前点击的是否被选中
        const selected = this.multipleSelection.some(item => item.id === row.id)  // 是取消选择还是选中
        if (!selected) { // 不包含   代表选择
          this.multipleSelection.push(row)
          this.$refs['multipleTable'].toggleRowSelection(row, true);
        } else { // 取消选择
          var finalArr = this.multipleSelection.filter((item) => {
            return item.id !== row.id
          })
          this.multipleSelection = finalArr  // 取消后剩余选中的

          this.$refs['multipleTable'].toggleRowSelection(row, false);
        }
        console.log('更改选择后', this.multipleSelection)
    },
           
2、点击行单选
vue elementUI实现el-table点击行单选, 点击行多选,点击复选框单选效果
rowClick(row, column, event) {
      // console.log(row)
      //   选已选中数据中判断当前点击的是否被选中
      if (this.multipleSelection[0] == row) {  // 选中的是已有的 取消选中
        this.multipleSelection = [];
        this.$refs['Table'].clearSelection();
      } else {
        this.multipleSelection = [row];
        this.$refs['Table'].clearSelection();
        this.$refs['Table'].toggleRowSelection(row, true);
      }
    },
           
3、table复选框单选     点击复选框单选效果    记录选中数据
handleSelectionChange(selection, row) {
      if (this.multipleSelection[0] == row) {
        this.multipleSelection = [];
        this.$refs['Table'].clearSelection();
      } else {
        this.multipleSelection = [row];
        this.$refs['Table'].clearSelection();
        this.$refs['Table'].toggleRowSelection(row, true);
      }
    },
           
4、table复选框多选       点击复选框多选效果       记录选中数据
selectChange(selection, row) {
      // console.log('手动勾选数据行', selection, row)
      // 判断当前行是否选中
      const selected = selection.some(item => item === row)  // 是取消选择还是选中
      if (selected) { // 选择
        this.multipleSelection.push(row)
      } else { // 取消选择
        var finalArr = this.multipleSelection.filter((item) => { 
          return item.id !== row.id
        })
        this.multipleSelection = finalArr
      }
      console.log('更改选择后', this.multipleSelection)
    },
           

如果还涉及到复选框默认勾选,默认禁用等效果。

可查看我的上篇笔记~

继续阅读