element-ui 的el-table,多选翻页后,之前选择的数据丢失问题处理
问题描述
在使用Element UI的el-table
组件时,开启多选功能后,当切换分页或重新加载数据时,之前选中的数据会丢失。这是由于表格在重新渲染时未保留之前的选择状态。
解决方案
1.手动存储历史
利用一个数组来保存所有选中的数据,而不仅仅是当前页的数据。
<el-tableref="multipleTable":data="tableData"@select = "rowSelectChange"
><el-table-columntype="selection"width="55"></el-table-column><!-- 其他列 -->
</el-table><script>
const ids = ref([])
const rowSelectChange=(selection: UserVO[], row: UserVO)=>{// 判断是否选中,选中ids增加,取消选中ids删除if(selection.filter(item=>item.userId == row.userId).length>=1){ids.value.push(row.userId)}else{ids.value = ids.value.filter(item=>item!=row.userId)}
}const initIds=()=>{// initSelectUsers 为默认已经选中的idsprops.initSelectUsers?.forEach(userItem => {ids.value.push(userItem)});
}
</script>
2.使用row-key和reserve-selection
对于需要跨页保持选中状态的场景,可以给表格设置row-key
并启用reserve-selection
属性。这需要确保每行数据有唯一标识(如id
)。
<el-tableref="multipleTable":data="tableData":row-key="getRowKeys"@selection-change="handleSelectionChange"
><el-table-columntype="selection"width="55":reserve-selection="true"></el-table-column><!-- 其他列 -->
</el-table><script>
const ids = ref([])
const handleSelectionChange = (selection: UserVo) => {ids.value = selection.map((item) => item.userId);
}
const getRowKeys=(row:UserVO)=>{return row.userId;
}
</script>
注意事项
- 使用
reserve-selection
时,必须指定row-key
且数据中的该字段必须唯一。 - 跨页选中会占用内存,数据量过大时建议采用服务器端保存选中状态。
总结
以上可以有效解决分页时选中丢失的问题,对于简单场景,使用reserve-selection
属性更为便捷,如果需要修改原有历史数据数组保存 数据更方便。