el-table多选(Checkbox)控制

el-table多选控制,这个需求提及概率挺多的,有些细节点过后就容易忘记,这里马克下,方便下次遇到了直接cv

  • 需要注意的点:this.$refs.multipleTable.toggleRowSelection执行,会同时触发@selection-change事件;
  • :row-key="getRowKeys"用于解决,重新请求列表接口,能保持上次的勾选记录;
  • this.$refs.multipleTable.toggleRowSelection必须是tableList的原始值,不能是复制的值;
  • highlight-current-row:是否要高亮当前行
  • :selectable:仅对 type=selection 的列有效,类型为 Function,Function 的返回值用来决定这一行的 CheckBox 是否可以勾选
<el-table
        ref="multipleTable"
        v-loading="loading"
        :max-height="550"
        :data="tableList"
        fit
        border
        @sort-change="sortChange"
        highlight-current-row
        :row-key="getRowKeys"
        @selection-change="handleSelectionChange"
      >
<el-table-column
        type="selection"
        :selectable="handleIsSelect"
        width="40">
      </el-table-column>
  <el-table-column
          width="150"
          prop="device_employee_name"
          sortable="device_employee_name"
          label="设备负责人"
          show-overflow-tooltip
        >
        </el-table-column>
</el-table>

data() {
      return {
        listLoading: false,
        tableList: [],
        page_size: 20,
        page: 1,
        searchForm: {
          order_field: '',
          sort_type: '',
        },
        // 获取row的key值
        getRowKeys(row) {
          return row.id
        },

        tableList: []
      }
    },
async initTable(val = 1) {
        this.listLoading = true

        const options = {
          ...this.searchForm,
          page_size: this.page_size,
          page: val,
        }

        let res = await this.$http('soc.sas.oa.fortressApplyList', options, { appkey: 55066 })
        this.listLoading = false
        this.total = res.total_rows
        this.searchForm.page = res.page
        this.tableList = res.rows

        // 过滤
        const ids = this.multipleSelectTableData.map(item => item.id)
        // 勾选
        this.$nextTick(() => {
          this.tableList.forEach(item => {
            if (ids.includes(item.id)) {
              this.$refs.multipleTable.toggleRowSelection(item, true)
            }
          })
          this.isCreatedFlag = false
          this.multipleSelectData = this.multipleSelectTableData
        })
      },

// 排序,注意这里的排序sortable和prop要一致
sortChange(v) {
        if (!v.order) {
          this.searchForm.order_field = ''
          this.searchForm.sort_type = ''
        } else {
          if (v.order === 'descending') {
            this.searchForm.sort_type = 'desc'
          } else {
            this.searchForm.sort_type = 'asc'
          }
        }
        this.initTable()
      },

// 勾选的回调函数,返回全部勾选值
handleSelectionChange(val) {
        this.multipleSelectData = val
      },
// 当前选中批量激活,且为未完成状态,则可勾选,否则不可勾选
    handleIsSelect(row) {
      if(this.isBatchActivate){
        return row.status === 0
      }else {
        return true
      }
    },

推荐阅读更多精彩内容