实现思路:
1:定义一个数组,用来存储全部已勾选数据selectedInfo[]
2:利用三个双重for循环进行处理selectedInfo里面的数据
(一):外层循环为当前页数据(userList),内层循环为当前页选中数据(value,根据element ui table自带方法selection-change可以获取)
选中数据存入selected,未选中存入unselected
const userList = JSON.parse(JSON.stringify(this.loginUserInfo))//当前页数组
userList.map((item) => {
const b = value.find(it => item.userName === it.userName);
if(b) {
selected.push(item);
}else {
unSelected.push(item);
}
});
(二):外层循环为当前页选中数据(selected),内层循环为全部已勾选数据(selectedInfo)
通过唯一标识进行判断,将selectedInfo中没有的数据存入
selected.map((item) => {
const b = this.selectedInfo.find(it => item.userName === it.userName);
if(!b) {
this.selectedInfo.push(item);
}
});
(三):外层循环为当前页未选中数据(unselected),内层循环为全部已勾选数据(selectedInfo)
通过唯一标识进行判断,将selectedInfo中有的数据进行删除
unSelected.map((item) => {
this.selectedInfo.map((it, index) => {
if(item.userName === it.userName) {
this.selectedInfo.splice(index, 1);
}
})
});
3:在table分页接口调用时要对选中的数据进行回显
在调用后端接口成功后,利用双重for循环进行回显
外层循环为全部已勾选数据(selectedInfo),内层循环为当前页数据
通过唯一标识进行判断,将selectedInfo中有的数据,通过element ui table自带方法toggleRowSelection()进行回显
this.stopReBack = true;
setTimeout(() => {
this.selectedInfo.map((item) => {
const b = this.loginUserInfo.find(it => item.userName === it.userName);
if(b) {
this.$refs.multipleTable.toggleRowSelection(b, true);
}
});
this.stopReBack = false;
}, 50);
注:(1)toggleRowSelection方法入参不能用item,一定要用b,因为看似item和b是相同的,但是会有细微差别,导致回显不成功
(2)为了防止回显成功前对表格进行操作,定义变量stopReBack,在回显成功前将stopReBack置为true,回显成功后将stopReBack置为false
综上所述,selection-change方法全部带码为:
loginUserCheckboxed(value){
if(this.stopReBack) {
return false;
}
const userList = JSON.parse(JSON.stringify(this.loginUserInfo))//当前页数组
const selected = [];
const unSelected = [];
userList.map((item) => {
const b = value.find(it => item.userName === it.userName);
if(b) {
selected.push(item);
}else {
unSelected.push(item);
}
});
selected.map((item) => {
const b = this.selectedInfo.find(it => item.userName === it.userName);
if(!b) {
this.selectedInfo.push(item);
}
});
unSelected.map((item) => {
this.selectedInfo.map((it, index) => {
if(item.userName === it.userName) {
this.selectedInfo.splice(index, 1);
}
})
});
},