table 表格选择中,分页后状态保留

193 阅读1分钟

table 表格选择中,分页后状态保留

image.png


    <el-table v-loading="loading"
              :data="shopOrderList"
              @selection-change="handleSelectionChange"
              @select-all="selectAll"
              :row-key="getRowKey"
              @select='selectRows'
              ref="typeTable"
              class="order-table">
      <el-table-column type="selection"
                       width="55"
                       :reserve-selection="true"
                       align="center"
                       fixed />
                        </el-table>

注意回显的两个参数 row-key与reserve-selection 作为绑定的。

    getRowKey (row) {
      return row.id
    },

选中 触发 函数

  /** 单项 这里的选中判断初始化都未选中
     * 第一次没有 push
     * 第二次有 排他
     * */
    selectRows (selection, row) {
      console.log(row.id, 'selection, row 单选')
      if (this.selectExportId.find((i) => i === row.id)) {
        this.selectExportId = this.selectExportId.filter((i) => i != row.id);
        this.selectOrderGoods = this.selectOrderGoods.filter((i) => i.id != row.id);
      } else {
        this.selectExportId.push(row.id);
        this.selectOrderGoods.push(row)
      }

      console.log(this.selectExportId, 'selectExportId')

    },
    
        // 全部
    selectAll (rows) {
      console.log(rows, '全选')
      if (rows.length) {
        // 收集 已经选择 id
        rows.forEach((row) => {
          if (!this.selectExportId.find((item) => item == row.id)) {
            this.selectExportId.push(row.id);
          }
        });
        // 收集 选中对象
        rows.forEach((row) => {
          if (!this.selectOrderGoods.find((item) => item.id == row.id)) {
            this.selectOrderGoods.push(row);
          }
        });
      } else {
        this.shopOrderList.forEach((row) => {
          this.selectExportId = this.selectExportId.filter(
            (item) => item != row.id
          );
        });
        this.shopOrderList.forEach((row) => {
          this.selectOrderGoods = this.selectOrderGoods.filter(
            (item) => item.id != row.id
          );
        });
      }
    },
    
    

我们就拿到选择 id 和 选中的每个对象 在分页触发调用的更新函数 内调用 tbale 内置的 toggleRowSelection 方法

     // 数据回显
      this.$nextTick(() => {
        //  选中的表格 多选 回显的方法 根据id进行回显的
        this.shopOrderList.forEach((item, index) => {
          if (this.selectExportId.findIndex((i) => i === item.id) >= 0) {
            this.$refs.typeTable.toggleRowSelection(
              this.$refs.typeTable.data[index],
              true
            );
          }
        })
      })