element-ui 的table表格可以轻松实现多选的功能,只要在表格列中增加type="selection"的一列即可。
但是大部分情况下,表格的数据是有分页的,分页一般是要请求后台接口,这样上一页也就是上一次请求的数据的选中状态就没有了。element-ui提供了reserve-selection,可以保存数据更新前选中的值,这个属性还需要指定row-key。
<template>
<div>
<el-table ref="userTable"
:data="userList"
:row-key="getRowKeys"
@selection-change="userSelectionChange">
<el-table-column type="selection" :reserve-selection="true"></el-table-column>
<el-table-column prop="account" label="账号"></el-table-column>
<el-table-column prop="phone" label="手机"></el-table-column>
<el-table-column prop="email" label="邮箱"></el-table-column>
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="userPageObj.currentPage"
:page-sizes="[10,20,30]"
:page-size="userPageObj.pageSize"
layout="total, sizes, prev, pager, next"
:total="userPageObj.total">
</el-pagination>
</div>
</template>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
<script>
export default {
data() {
return {
userList: [],
userPageObj: {
currentPage: 1, //当前页
pageSize: 10, //每页条数
total: 0, //数据总数
},
}
},
methods: {
//加载用户列表
getUserList() {
//调接口,赋值,具体细节省略
},
getRowKeys(row) {
return row.account;
},
userSelectionChange(arr) {
console.log(arr);
},
},
mounted() {
this.getUserList();
},
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
假如第1页选中3项,切换分页到第2页选中2项,看最后console.log(arr)的数据:
如果不设置reserve-selection=“true”,则最终console的结果是:第2页的2条数据;
如果设置reserve-selection=“true”,则最终console的结果是:第1页的3条数据 + 第2页的2条数据 = 5条数据。