记录El-table 选中数据 以及 数据回显

550 阅读1分钟

分页选中

<el-table :row-key="(row: any) => row.id">
     <el-table-column type="selection" :reserve-selection="true"></el-table-column>
</el-table>

El-table 的全部属性

<el-table
          :data="tableData"
          ref="tableRef"
          border
          stripe
          :row-key="(row: any) => row.id"
          @select="handleSelectRow"
          @select-all="handleSelectAll"
          show-overflow-tooltip
          >
  ******
</el-table>

获取选中数据

单选:判断单选是选中还是取消选中

const handleSelectRow = (selection: any, row: any) => {
    let selected = selection.includes(row)
    if (selected) {
        checkoutList.value.push(row)
    } else {
        checkoutList.value = checkoutList.value.filter((item: {id: number}) => item.id !== row.id)
    }
}

多选 :判断单选是选中还是取消选中

const handleSelectAll = (selection: any) => {
    if (getIsAllChecked()) {
        // 全选
        checkoutList.value = [...checkoutList.value, ...selection]
    } else {
        // 取消全选
        let tableDataIds = tableData.value.map((item: {id: number}) => item.id) // 当前页的ids
        // 去除选中列表中 当前页取消选中的数据
        checkoutList.value = checkoutList.value.filter((item: {id: number}) => !tableDataIds.includes(item.id)) 
    }
}
​
// 获取table组件中的全选checkbox的勾选状态
const getIsAllChecked = () => {
    return tableRef.value.store.states.isAllSelected.value
}

反显数据

// checkoutIds : 选中ids
tableData.value.forEach((item: any) => {
  if (checkoutIds.value?.includes(item.id)) {
    tableRef.value.toggleRowSelection(item, true)
  }
})