实现在翻页表格调用接口后,仍保持上一页选中状态
<el-table
ref="table"
:data="tableList"
:border="true"
row-key="id"
@selection-change="handleSelectionChange"
@select="handleSelect"
>
<el-table-column
type="selection"
:reserve-selection="true"
width="40px"
align="center"
/>
</el-table>
@select 方法在用户勾选中数据时触发,参数 row 可获取到当前选中行数据
data() {
return {
// 用于存放被选中数据
selectionList: []
}
},
handleSelect(selection, row) {
// 获取点击行是否被选中
const isChecked = this.$refs.table.selection.includes(row)
if (isChecked === true) {
// 如果被选中 判断数组中是否有相同id
const isIdDuplicate = this.selectionList.some(
(item) => item.id === row.id
)
// 没有相同id则添加到数组中
if (!isIdDuplicate) {
this.selectionList.push(row)
}
} else {
// 如果取消勾选 则从数组中移除
this.selectionList = this.selectionList.filter(
(item) => item.id !== row.id
)
}
}
在调用接口方法内
//查询列表信息方法
registerQuery() {
// 如果数组内有数据 则将数据传入setTabelSelected内
if (this.selectionList.length > 0) {
this.setTabelSelected(this.selectionList)
}
},
// rows 存放选中的数据
setTabelSelected(rows) {
if (rows.length > 0) {
this.$nextTick(() => {
for (let i = 0; i < this.tableList.length; i++) {
let item = this.tableList[i]
for (let j = 0; j < rows.length; j++) {
let row = rows[j]
if (row.id == item.id) {
this.$refs.table.toggleRowSelection(item, true)
break
} else {
this.$refs.table.toggleRowSelection(item, false)
}
}
}
})
} else {
this.$nextTick(() => {
this.$refs.table.clearSelection()
})
}
}