Vue使用element中table组件实现单选一行

Vue使用element中table组件实现单选一行

实现起来其实很简单,官方已经给了我们一个很好的例子。
在这里插入图片描述
看懂这个案例我们就可以实现单选。
html:

<div style="margin-top: 20px">
    <el-button @click="toggleSelection([tableData[1], tableData[2]])">切换第二、第三行的选中状态</el-button>
    <el-button @click="toggleSelection()">取消选择</el-button>
</div>

js:

	toggleSelection(rows) {
    
    
        if (rows) {
    
    
          rows.forEach(row => {
    
    
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
    
    
          this.$refs.multipleTable.clearSelection();
        }
      },
	handleSelectionChange(val) {
    
    
        this.multipleSelection = val;
      }
    }

当点击第一个按钮的时候,实参为,列表的第二个,第三个对象,在具体的实现方法里面进行了循环,使用了ref来绑定table,

this.$refs.multipleTable.toggleRowSelection(row);

row为每一行的对象。 这样就实现了将第二行与第三行选中的效果。
在这个方法里面,如果不传形参的话,会进行清除选中操作:

this.$refs.multipleTable.clearSelection();

因此:

我们要实现单选的话,思路就是在每次点击的时候,都判断当前选中了几个,超过一个的话,清除所有选中,然后将最后一个选中。

    // 选中行返回选中信息
    getSelectRowFun(rows) {
    
    
      if (rows.length === 0) return;
      if (this.flag === "single" ) {
    
    
        this.$refs.multipleTable.$children[0].clearSelection();
        this.$refs.multipleTable.$children[0].toggleRowSelection(
          rows && rows.pop()
        );
      }
    },

在这里插入图片描述
实现。

猜你喜欢

转载自blog.csdn.net/qq_43291759/article/details/125911401