element-ui table 复选框判断选中还是未选中及默认值的填充

前提:

当我们列表数据使用分页进行展示时,我们需要使用到复选功能并在切换分页后需要保留之前的选中数据的情况下,使用 element-ui table 自带的 selection-change 是无法满足保留之前数据筛选状态的。 可以通过 select 和 select-all 事件来进行该功能开发

1. element-ui table的复选框判定选中状态

在 element-ui官网 中的table组件提供的事件中可以使用 select 事件来进行判断

具体代码如下:

<el-table
    ref="videoEnterpriseList"
    :data="list1"
    style="width: 100%"
    @select="handleSelection"
>
    <el-table-column type="selection" width="50px" />
</el-table>
// 列表复选功能-单选
handleSelection(selectionArr, item) {
    const self = this
    // selectionArr-勾选的数据
    // item-当前点击的数据
    // 在selectionArr中寻找item,checkedVal = false未选中,checkedVal  = true 选中
    const checkedVal = selectionArr.find(x => x.cameraId === item.cameraId)
    const sIndex = self.selection.indexOf(item.cameraId)
    if (!checkedVal) {
        // 未选中要做的事情
        if (sIndex > -1) {
          self.selection.splice(sIndex, 1)
        }
    } else {
        // 选中要做的事情
        if (sIndex === -1) {
          self.selection.push(item.cameraId)
        }
    }
}

 使用 select 只针对单行数据的选择和取消,表头的全选去进行勾选的和取消就会出现问题

 全选问题解决方案:

在 element-ui官网 中的table组件提供的事件中可以使用 select-all事件来进行判断

 通过select-all 我们可以获取到当前页数据是全选了还是全部未选,具体代码如下

// 列表复选功能-全选
handleSelectionAll(selection) {
    const self = this
    if (selection.length === 0) {
        // 全部都不勾选
        // this.list1 是列表当前页的数据
        // self.selection 是已经勾选的数据
        this.list1.forEach((x) => {
          const sIndex = self.selection.indexOf(x.cameraId)
          if (sIndex > -1) {
            self.selection.splice(sIndex, 1, 'delete')
          }
        })
        self.selection = self.selection.filter((item) => item !== 'delete')
    } else {
        selection.forEach((x) => {
          const sIndex = self.selection.indexOf(x.cameraId)
          if (sIndex > -1) {
            self.selection.splice(sIndex, 1, 'delete')
          }
        })
        self.selection = self.selection.filter((item) => item !== 'delete')
        selection.forEach((x) => {
          self.selection.push(x.cameraId)
        })
    }
}

2. element-ui table的复选框默认值填充

element-ui官网 中的table组件提供了 toggleRowSelection 方法进行复选框的数据回填

 具体使用代码如下:

1.  注意:如果当前列表数据存在分页,那么选中的数据id集合是所有的选中数据,不是当前页选中的数据id集合

data() {
    return {
        list1: [], // 列表当前数据
        selection: [] // 列表选中数据id集合
    }
}

 2. 将当前的列表数据和选中的id集合进行比对,id存在就使用 toggleRowSelection 方法进行选中处理

this.list1.forEach(x => {
    if (this.selection.indexOf(x.cameraId) > -1) {
        this.$refs.videoEnterpriseList.toggleRowSelection(x, true)
    }
})

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值