需求:
1.表格多选
2.支持翻页
3.支持当前页全选
效果如下:
IMG.jpeg
思路:
1.将每页全部选中的数据存放到一个数组中
2.将当前页码选中的数据存到一个数组中
3.获取一个键值,标识当前行的唯一键的名称
实现:
1.初始化数据
driver_id:[],
multipleSelectionAll:[],//所有选中的数据包含跨页数据
multipleSelection:[],// 当前页选中的数据
idKey: 'driver_id', // 标识列表数据中每一行的唯一键的名称
2.复选框改变时的事件
//复选框
handleSelectionChange(val){
let driver_ids =[];
val.map(item =>{
driver_ids.push(item.driver_id);
})
this.form.sels = driver_ids.join(',');
this.driver_id = driver_ids
this.multipleSelection = val;
this.multipleSelectionAll = Array.from(new Set(this.multipleSelectionAll.concat(driver_ids))); // 去重
//实时记录选中的数据
setTimeout(()=>{
this.changePageCoreRecordData();
}, 50)
},
3.翻页记忆核心部分:
// 记忆选择核心方法
changePageCoreRecordData () {
// 标识当前行的唯一键的名称
let idKey = this.idKey;
let that = this;
// 如果总记忆中还没有选择的数据,那么就直接取当前页选中的数据,不需要后面一系列计算
if (this.multipleSelectionAll.length < 0) {
this.multipleSelectionAll = this.multipleSelection;
return;
}
// 总选择里面的key集合
let selectAllIds = [];
this.multipleSelectionAll.forEach((row,index)=>{
selectAllIds.push(row[idKey]);
})
let selectIds = []
// 获取当前页选中的id
this.multipleSelection.forEach(row=>{
selectIds.push(row[idKey]);
// 如果总选择里面不包含当前页选中的数据,那么就加入到总选择集合里
if (selectAllIds.indexOf(row[idKey]) < 0) {
that.multipleSelectionAll.push(row);
}
})
let noSelectIds = [];
// 得到当前页没有选中的id
this.tableData.forEach(row=>{
if (selectIds.indexOf(row[idKey]) < 0) {
noSelectIds.push(row[idKey]);
}
})
noSelectIds.forEach(id=>{
if (selectAllIds.indexOf(id) >= 0) {
for(let i = 0; i< that.multipleSelectionAll.length; i ++) {
if (that.multipleSelectionAll[i][idKey] == id) {
// 如果总选择中有未被选中的,那么就删除这条
that.multipleSelectionAll.splice(i, 1);
break;
}
}
}
})
let driver_id =[];
this.multipleSelectionAll.map(item => {
driver_id.push(item.driver_id);
})
this.form.sels = driver_id.join(',');
if(this.multipleSelectionAll.length > this.total) {
let ID = this.multipleSelectionAll[this.multipleSelectionAll.length - 1].driver_id
this.tableData.forEach(row=>{
if(row.driver_id == ID) {
this.$refs.multipleTable.toggleRowSelection(row); //实现打钩
}
})
}
},
4.请求翻页重新取得数据时再次勾选上记忆中的选项
setSelectRow() {
if (!this.multipleSelectionAll || this.multipleSelectionAll.length < 0) {
return;
}
// 标识当前行的唯一键的名称
let idKey = this.idKey;
let that = this;
if(this.selectAllIds!=null){
this.$refs.multipleTable.clearSelection();
for(var i = 0; i < this.tableData.length; i++) {
if (this.selectAllIds.indexOf(this.tableData[i][idKey]) >= 0) {
// 设置选中,记住table组件需要使用ref="multipleTable"
this.$refs.multipleTable.toggleRowSelection(this.tableData[i], true);
}
}
}
},
前端小白一枚,希望能够帮到你,欢迎留言评论!
喜欢的点赞和关注哦!!