被这个害惨了 el-table+tree 全选 反选 选不中子级

75 阅读1分钟

被这个害惨了 el-table+tree 全选 反选 选不中子级

image.png 一开始一直是这样的 各种搜 就是找不到解决办法 要不然就是不一样 没办法 只能自己来了

因为代码不方便透漏 直接写一个小demo吧

<el-table
      ref="tables"
      v-loading="loading"
      border
      stripe
      @select-all="selectAll"
      @select="select"
      :data="dataList"
      style="width: 100%"
      row-key="id"
      :tree-props="{ children: 'children' }"
    >
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column
        type="index"
        label="序号"
        width="80"
        align="center"
        sortable
      />
      <el-table-column
        label="评审项目"
        align="left"
        width="130"
        prop="date"
        sortable
      />
      <el-table-column label="评审类型" align="left" prop="name" />
      <el-table-column label="评审类型" align="left" prop="address" />
    </el-table>
    
    //这是el-table中的代码  row-key="id"       :tree-props="{ children: 'children' }"这两个是必须要加的
export default {
  data() {
    return {
      dataList: [], //这里的数据直接去element-ui中拿就行
    };
  },
  methods: {
    selectAll(selection) {
      //这个方法会在点击表头的全选复选框时被调用。selection 参数是当前已选中的行数组。
      if (selection.length === this.dataList.length) {
        let rows = [];
        this.getChildren(rows, this.dataList);
        rows.forEach((row) => {
          this.$refs.tables.toggleRowSelection(row, true);
        });
        //如果 selection.length 等于 this.dataList.length,说明当前已选中的行数量等于表格中的总行数,
        //即所有行都被选中。此时,我们需要将所有的子级行也全部选中。为此,我们遍历所有的行,包括嵌套的子级行,
        //将它们全部添加到 rows 数组中,然后使用 this.$refs.tables.toggleRowSelection(row, true) 
        //来将它们全部选中。
      } else {
        let rows = [];
        this.getChildren(rows, this.dataList);
        rows.forEach((row) => {
          this.$refs.tables.toggleRowSelection(row, false);
        });
        //如果 selection.length 不等于 this.dataList.length,说明并不是所有行都被选中。
        //此时,我们同样遍历所有的行,将它们全部添加到 rows 数组中,
        //然后使用 this.$refs.tables.toggleRowSelection(row, false) 来将它们全部取消选中。
      }
    },
    select(selection, row) {
      //这个方法会在点击表格行的复选框时被调用。selection 参数是当前已选中的行数组,row 参数是点击的行。
      let rows = [];
      this.getChildren(rows, row.children);
      rows.forEach((childRow) => {
        this.$refs.tables.toggleRowSelection(childRow);
      });
      //对于子级行的处理,我们需要遍历当前行的所有子级行,将它们全部添加到 rows 数组中,
      //然后使用 this.$refs.tables.toggleRowSelection(childRow) 来切换子级行的选中状态。
    },
    getChildren(rows, children) {
      //这个方法是一个递归函数,用于获取当前行的所有子级行。它接收两个参数,rows 是一个数组,
      //用于存储子级行,children 是当前行的子级行数组。
      if (children) {
        children.forEach((child) => {
          rows.push(child);
          this.getChildren(rows, child.children);
        });
      }
      //如果当前行有子级行(即 children 存在),我们会遍历每个子级行,将它们添加到 rows 数组中,
      //然后递归调用 getChildren(rows, child.children) 来获取子级行的子级行。
    },
  },
};