场景:对数据表格中数据进行选取,然后保存的数据操作。
对于数据表格,貌似这种需求不是非常常用,对于小数据量来说,checkbox就已经能够足够满足我们的要求,但往往对于大数据量可能需要通过表格来实现选择。
在 el-table
的 Table-column Attributes
中有这么一个属性:
属性 | 描述 | 类型 | 可选值 | 默认值 |
---|---|---|---|---|
reserve-selection | 仅对 type=selection 的列有效,类型为 Boolean,为 true 则会在数据更新之后保留之前选中的数据(需指定 row-key) | Boolean | — | false |
不过需要指定行的key,我们可以在el-table
上加上一个row-key
属性来指定key
最终代码如下
<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>
下面提供分页多选且赋初始选中的方案
<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>