el-table 后端分页,支持跨页勾选以及回显

3,705 阅读1分钟

需求:业务中绑定一对多关系的场景;采用表格展示数据,支持跨页勾选;若已存在绑定关系,先回显当前绑定关系;支持用户在已选与全部数据间切换查看;但由于数据量大,必须采用后端分页;

方法一

采用官方提供的 row-key、reserve-selection
在使用下,表格的全选框是针对表格所有数据的;由于后端是分页数据,在回显数据时,有些情况下全选框效果会给用户前后不一致的效果,如下图(不推荐)

全选框状态.gif

方法二

将表格全选框调整为针对表格当前页数据,通过添加当前选中数量展示来告知除当前页外还有数据绑定关系 实现效果如下图

跨页勾选.gif

具体实现

  • 获取已经绑定的数据 id 数组,获取表格当前页数据,比对勾选
//获取表格当前页数据
getList(){
    // 异步请求(支持指定 id 等过滤条件)
    .......
    this.$nextTick(()=>{
        let checkRow;
        // selectIdList 维护的是已绑定的数据 id
        this.selectIdList.slice().forEach(instanceId => {
          checkRow = this.tableData.find(item => item.instanceId === instanceId);
          if(checkRow){
            this.$refs.elTable.toggleRowSelection(checkRow, true);
          }
        });
    })
}
  • 区分单行、当前页勾选与取消勾选,维护表格全量数据中勾选数据
 select(selection, row){
  const isAdd = selection.some(selectRow => selectRow.instanceId === row.instanceId);
  this.rowChangeAll(row, isAdd);
},
selectAll(selection){
  let isAdd = true;
  let changeSelect = selection.slice();
  if(!changeSelect.length){
     // 取消当前页全选,获取表格当前页所有数据
    isAdd = false;
    changeSelect = this.tableData.slice();
  }
  // 全选时,存在之前已经选上;只加不删
  changeSelect.forEach(row =>{
    this.rowChangeAll(row, isAdd);
  });
},
rowChangeAll(row, isAdd){
  const index = this.selectIdList.indexOf(row.instanceId);
  if(index === -1){
    if(isAdd){
      this.selectIdList.push(row.instanceId);
    }
  }else{
    if(!isAdd){
      this.selectIdList.splice(index, 1);
    }
  }
},
  • 已选数据维护,以及点击查看获取已选数据
computed:{
    checkNum(){
      return this.selectIdList.length;
    }
},
methods: {
    showClicked(){
      this.isSelectAll = !this.isSelectAll;
      if(!this.isSelectAll && !this.checkNum){
        // 查看已选 && 无资源id   不查询
        this.tableData = [];
        this.total = 0;
        return;
      }
      this.getList();
    },
}
  • 右上角过滤条件,维护好过滤条件,调用 getList 函数即可