Keep pagination selected in el-table

Scenario: Select data in the data table and then save the data operation.

For data tables, it seems that this requirement is not very common. For small amounts of data, checkbox is enough to meet our requirements, but for large amounts of data, it is often necessary to use tables to achieve selection.

el-tableThere is such an attribute in Table-column Attributes:

Attributes describe type Optional value Defaults
reserve-selection It is only valid for columns with type=selection. The type is Boolean. If it is true, the previously selected data will be retained after the data is updated (row-key needs to be specified) Boolean false

However, we need to specify the key of the row. We can el-tableadd an row-keyattribute to specify the key.

The final code is as follows

<template>
	<el-table ref="dataTable" :data="tableList" :row-key="getRowKeys" border>
		<el-table-column type="selection" width="55" reserve-selection></el-table-column>
	</el-table>
</template>

<script>
	export default {
		data() {
			return {
				tableList: []
			}
		},
		methods: {
			// 获取行的key,用于表格保留分页选中
			getRowKeys(row) {
				return row.id;
			}
		}
	}
</script>

The following provides a solution for paging multiple selections and assigning initial selections.

<template>
	<el-table ref="dataTable" :data="tableList" :row-key="getRowKeys" @select="handleSelectionChange" border>
		<el-table-column type="selection" reserve-selection></el-table-column>
	</el-table>
</template>

<script>
	import service from './service'
	export default {
		data() {
			return {
				tableList: [], // 表格数据
				defaultSelectedIds: [], // 默认选中数据ID
				multipleSelection: [] // 选中的所有行数据
			}
		},
		methods: {
			// 获取行的key,用于表格保留分页选中
			getRowKeys(row) {
				return row.id;
			},
			handleSelectionChange(selection, row) {
				// 判断如果是取消选中,且在defaultSelectedIds中含有的,则删掉
				const index = this.defaultSelectedIds.indexOf(row.id);
				if (this.multipleSelection.length > selection.length && index !== -1) {
					this.defaultSelectedIds.splice(index, 1);
				}
				this.multipleSelection = selection;
			},
			getTableList() {
				service.getDataList().then(res => {
					this.tableList = res.list;
					
					// 判断在defaultSelectedIds中含有的,通过方法去选中,保留defaultSelectedIds是因为defaultSelectedIds中的值无法对全部页选中
					this.$nextTick(() => {
						if (this.tableList && this.defaultSelectedIds) {
							this.tableList.forEach(row => {
								if (this.defaultSelectedIds.includes(row.id)) {
									this.multipleSelection.push(row);
									this.$refs.dataTable.toggleRowSelection(row, true);
								}
							});
						}
					});
				});
			}
		}
	}
</script>

Guess you like

Origin blog.csdn.net/jl15988/article/details/132605296