场景:el-table采用分页的形式,并且数据可进行多选,的那个切换页数时,勾选的数据可保留可回显选中。
解决方法:通常采用select和select-all事件实现,select事件可处理当前行选中情况,select-all事件可处理table是否点击全选按钮。具体主要代码如下:
<el-table
ref="multipleTable"
:data="pageList"
style="width: 100%"
height="100%"
v-loading="dialogLoading"
row-key="uniqueId"
@select="handleSelectRow"
@select-all="handlerSelectAll"
:row-class-name="disabledClass"
>
<el-table-column type="selection" width="55" :selectable="selectable">
</el-table-column>
//省略其他列数据
</el-table>
//获取当前页的列表
async getList() {
this.pageList = data
this.$nextTick(() => {
//回显勾选项
this.pageList.forEach((item) => {
let findItem = this.selectedAllList.find((it) => {
return it.uniqueId === item.uniqueId
})
if (findItem) {
this.$refs.multipleTable.toggleRowSelection(item)
}
})
})
},
//选中/不选中全部
handlerSelectAll(val) {
if (val && val.length) {
if (this.selectedAllList && this.selectedAllList.length) {
//如果列表中不存在该项,则加入
val.forEach((item) => {
let findItem = this.selectedAllList.find((it) => {
return item.uniqueId === it.uniqueId
})
if (!findItem) {
this.selectedAllList.push(item)
}
})
} else {
this.selectedAllList = val
}
} else {
//为空的,需要删除选中数据中的该页数据
//场景:添加整页数据后又让其都不选中
this.pageList.forEach((item) => {
let findIndex = this.selectedAllList.findIndex((it) => {
return item.uniqueId === it.uniqueId
})
if (findIndex !== -1) {
this.selectedAllList.splice(findIndex, 1)
}
})
}
},
//选中/不选中单个
handleSelectRow(val, row) {
//findItem不存在,说明当前不选中,存在则说明当前选中
let findItem = val.find((item) => {
return item.uniqueId === row.uniqueId
})
//findIndex === -1,说明选中数据中不存在,否则存在
let findIndex = this.selectedAllList.findIndex((it) => {
return it.uniqueId === row.uniqueId
})
if (!findItem && findIndex !== -1) {
//该项不选中,将选中数据中存在的该项删除
this.selectedAllList.splice(findIndex, 1)
} else if (findItem && findIndex === -1) {
//该项选中,将选中数据中不存在的该项加入
this.selectedAllList.push(row)
}
},