1.场景描述:
antd的table表格数据有提供多选框的功能,只要设置rowSelection属性就可以选择表格的数据。但是有时候表格的数据是有分页的,分页一般是要重新请求后台数据,这样上一页的数据的选中状态就没有了。
解决办法:
antd提供了preserveSelectedRowKeys,类型为 Boolean,为 true时会在数据更新之后记住之前选择的数据。(需要指定rowKey)
html代码如下
<a-table
:loading="loadingShow"
:pagination="false"
:rowSelection="rowSelection"
:columns="columns"
:data-source="dataSource"
:scroll="{ x: scrollX ? scrollX : false, y: scrollY ? scrollY : false }"
:bordered="bordered"
:customRow="Dclick"
:size="'middle'"
:rowKey="(record) => record.id"
>
</s-table>
js代码
data() {
return {
select_rows: [], // 批量选中的行
selectedRowKeys: [], // 批量选中的key
};
},
computed: {
rowSelection() {
const { selectedRowKeys } = this;
return !this.hideCheckBox
? {
// preserveSelectedRowKeys: true, //翻页选择上一页数据办法1
columnWidth: this.columnWidth ? this.columnWidth : 100,
selectedRowKeys, // 一定要加上这一行代码,清除才会有作用
onChange: (selectedRowKeys, selectedRows) => {
// console.log(
// `selectedRowKeys: ${selectedRowKeys}`,
// 'selectedRows: ',
// selectedRows,
// );
this.selectedRowKeys = selectedRowKeys;
this.select_rows = selectedRows;
},
//翻页选择上一页数据办法2
onSelect: (record, selected) => {
console.log('勾选', selected);
selected
? this.selectedRowKeys.push(record)
: this.selectedRowKeys.splice(
this.selectedRowKeys.findIndex(x => x.id === record.id),
1,
);
},
onSelectAll: (selected, selectedRows, changeRows) => {
console.log('all');
this.selectedRowKeys = selected
? this.selectedRowKeys.concat(changeRows)
: this.selectedRowKeys.filter(
x => !changeRows.find(i => i.id === x.id),
);
},
}
: null;
},
},
this.selectedRowKeys 就是选中的数据