在 element-ui 的表格组件中,当进行分页加载数据时,如果需要保留前一页选择的数据,通常可以使用数组来保存所有已选择的数据,而不是只保存当前页的选中数据。
下面是一个参考示例,其中使用 selection
数组来保存选中数据,每次选择后都将选中的数据放到 selection
中,取消选择时则将对应的数据从 selection
中移除。当切换分页时,可以通过 selection
数组的内容来设置当前页的选中数据。
<template>
<div>
<el-table
:data="tableData"
:row-key="row => row.id"
@selection-change="handleSelectionChange"
>
<!-- 表头等省略 -->
<el-table-column
type="selection"
:selectable="row => row.enabled"
></el-table-column>
</el-table>
<el-pagination
:total="total"
:current-page="currentPage"
:page-size="pageSize"
@current-change="handleCurrentChange"
></el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
selection: [],
total: 100,
currentPage: 1,
pageSize: 10,
}
},
methods: {
// 触发表格选择事件时,将选中的数据添加到 selection 数组中
handleSelectionChange(selection) {
this.selection.push(...selection)
},
// 触发分页事件时,根据 selection 数组设置当前页的选中数据
handleCurrentChange(currentPage) {
this.currentPage = currentPage
// 根据选中数据设置当前页的选中状态
this.tableData.forEach(row => {
this.$refs.table.toggleRowSelection(row, this.selection.includes(row))
})
},
// 加载当前页的数据,如果该页中有已选中的数据,则设置其为选中状态
async loadData() {
// 省略获取数据的异步操作
const data = await fetchData(this.currentPage, this.pageSize)
// 将数据设置为表格的数据源
this.tableData = data.data
// 根据选中数据设置当前页的选中状态
this.tableData.forEach(row => {
this.$refs.table.toggleRowSelection(row, this.selection.includes(row))
})
}
},
mounted() {
// 加载第一页数据
this.loadData()
}
}
</script>
在上面的代码中,我们通过 selection
数组来保存选中数据,每当选择或取消选择某行时,将其加入或从 selection
移除,然后在切换分页时,根据 selection
数组来设置当前页的选中状态。再加载新数据时,如果选中的数据已经包含在新数据中,也会自动选中它们,因为在加载数据时 selection
数组的内容是不会丢失的。
需要注意的是,在这种情况下,因为多页数据的选中数据需要在各个页之间共享,所以不能使用内部状态 tableData
中的 selected
属性,这样的话只能保留当前页的选中数据。