element el-table表格切换分页保留分页数据+限制多选数量

发布于:2024-07-05 ⋅ 阅读:(18) ⋅ 点赞:(0)

el-table表格并没有相关的方法来禁用表头里面的多选按钮

在这里插入图片描述

那么我们可以另辟蹊径,来实现相同的多选+切换分页(保留分页数据)+ 限制多选数量的效果

<el-table
    :data="tableData"
    style="width: 100%">
    // 不使用el-talbe自带的多选功能
    //<el-table-column type="selection" width="55"></el-table-column>

	//自己单独建一个el-table-column 来设置选中状态
	<el-table-column fixed width="60">
       <template slot-scope="scope">
           <el-checkbox v-model="scope.row.isCheck"
              :disabled="selectable(scope.row)"
              @change="checkChange($event, scope.$index, scope.row)">
         </el-checkbox>
     </template>
    </el-table-column>
    <el-table-column
      label="日期"
      width="120">
      <template slot-scope="scope">{{ scope.row.date }}</template>
    </el-table-column>
</el-table>
//在获取表格数据以后 遍历表格,为每行数据添加上 isCheck 属性,并设置默认值false
this.tableData.forEach(item =>{
	item.isCheck = false;
})

实现多选功能 checkChange

 //事件有三个参数  
 // val el-checkbox change事件返回的值 代表 选中/不选中
 // index 当前tableData 所在的行
 // row 当前tableData 当前行的数据
 checkChange(val, index, row) {
 	  //通过val true/false ;来判断是 选中当前行/取消选中当前行
      if (val) {
        //选中 往多选数组里面推送
        this.multipleSelection.push(row);
      } else {
        //取消选中(删除) 拿到当前数据的唯一标识id 
        const { id } = row;
        let delIndex = this.multipleSelection.findIndex(
          (item) => item.id=== id
        );
        //删除 取消选中的数据
        if (delIndex !== -1) {
          this.multipleSelection.splice(delIndex, 1);
        }
      }
	  //重新设置 表格当前行的多选状态
      this.$set(this.tableData, index, { ...row, isCheck: !!val });
    },

实现 限制多选数量的功能 selectable(scope.row)

//我们在最上面的实例中定义了一个 el-checkbox的禁用方法  :disabled="selectable(scope.row)"

//限制最多只能选择5个
// 方法返回 true/false 来实现el-checkbox的禁用/选中功能
selectable(row) {
	  //限制多选最多只能选择5个
	  let limitNum = 5
      let ids = this.multipleSelection.map((item) => item.id);
      //判断当前行的唯一标识符 id,是否存在于多选数组中
      if (ids.includes(row.id)) {
        // 已选择的行,可取消禁用
        return false;
      } else if (ids.length >= limitNum  && !ids.includes(row.coilNo)) {
        // 超过最大选择条数,且当前行未被选中时,禁用
        return true;
      } else {
        // 其他情况下可选 取消禁用
        return false;
      }
}

实现切换分页保留分页数据功能

//获取表格数据
getTableData(){
	//模拟数据获取
	this.tableData = res.data || []

	//判断选中数组是否有值 有值(执行回显选中数据功能)
	if (this.multipleSelection.length > 0) {
         this.echoMultiple();
     }
}

//回显多选值
echoMultiple() {
	  //增加校验 如果当前tableData没有值 就不回显选中数据
      if (this.multipleSelection.length === 0 || this.tableData.length === 0) {
        return;
      }

      let ids = this.multipleSelection.map((item) => item.id) || [];
      this.tableData.forEach((item, index) => {
      	//遍历 tableData数值 找出符合要求的id
        if (ids.includes(item.id)) {
          // 为符合回显要求的数据 设置选中状态
          this.$set(this.tableData, index, { ...item, isCheck: true });
        }
      });
	  //避免视图不刷新 强制刷新视图
      this.$forceUpdate();
    }