element 表格分页 限制多选条数

效果图:

官方方法解释:

row-key

行数据的 Key,用来优化 Table 的渲染;在使用 reserve-selection 功能与显示树形数据时,该属性是必填的。类型为 String 时,支持多层访问:user.info.id,但不支持 user.info[0].id,此种情况请使用 Function
selection-change 当选择项发生变化时会触发该事件
selectable 仅对 type=selection 的列有效,类型为 Function,Function 的返回值用来决定这一行的 CheckBox 是否可以勾选
reserve-selection 仅对 type=selection 的列有效,类型为 Boolean,为 true 则会在数据更新之后保留之前选中的数据(需指定 row-key
   

案例:

<template>
  <div>
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          align="center"
          type="selection"
          :selectable="selectable"
          :reserve-selection="true"
          width="55">
      </el-table-column>
      <el-table-column min-width="200" prop="id" label="商品信息"></el-table-column>
    </el-table>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        tableData: [
          {id: 1},
          {id: 2},
          {id: 3},
          {id: 4},
          {id: 5},
          {id: 6},
          {id: 7},
          {id: 8},
          {id: 9},
        ],
        multipleSelectionList: [],
        limitNum: 2, //限制数量
      }
    },
    methods: {
      // 限制数量方法
      limitFn (list) {
        this.$refs.multipleTable.clearSelection();
        for (let i = 0; i < this.limitNum; i++) {
          this.$refs.multipleTable.toggleRowSelection(list[i]);
        }
      },
      // 判断复选框是否可以选择
      selectable (row) {
        let index = this.multipleSelectionList.findIndex(v => v.id === row.id)
        if (this.multipleSelectionList.length >= this.limitNum) {
          if (index !== -1) {
            return true
          } else {
            return false
          }
        } else {
          return true
        }
      },
      // 绑定表格key,用于翻页后也不会丢失表格状态
      getRowKey (row) {
        return row.id
      },
      // 回调表格选择的数据
      handleSelectionChange (list) {
        if (list.length > this.limitNum) {
          this.limitFn(list)
          return
        }
        this.multipleSelectionList = [...list];
      },
    }
  }
</script>

limitNum 就是需要限制的数量

猜你喜欢

转载自blog.csdn.net/weixin_41854372/article/details/116748998