问题:表格翻页上一页选择的数据丢失(采用的是后端分页每次翻页会直接刷新为新数据)
思路:给table渲染数据加上_checked=true,会显示已选中
主要代码:
@on-select="changes"
@on-select-cancel="handleCancelRow"
@on-select-all="handleSelectAll"
@on-select-all-cancel="handleCancelSelectAll"
this.selected是选择的所有数据
CODE是数据里辨识唯一的东西
别忘了在data里定义selected: [ ]
//数组去重
unique(arr){
const res = new Map();
return arr.filter((r) => !res.has(r.CODE) && res.set(r.CODE, 1))
},
//监听全选,有可能用户先单独选择了某几项,被我们push进去,然后再点了全选,因此数组合并需要去重一下
handleSelectAll(selection) {
this.selected = this.unique(this.selected.concat(selection));
},
//取消全选
handleCancelSelectAll() {
//this.table1_data2是当前页全部数据
this.table1_data2.forEach(r => {
this.selected.splice(this.selected.findIndex(item => item.CODE === r.CODE), 1)
})
},
//选择某一行
changes(val,row) {
this.selected.push(row);
},
// 取消某一行
handleCancelRow (selection,row) {
this.selected.splice(this.selected.findIndex(item => item.CODE === row.CODE), 1)
},
//把源数据加上_checked字段,遍历已选项数据,更新选中状态
updateChecked() {
for (var i = 0; i < this.table1_data2.length; i++) {
this.table1_data2[i]._checked = false;
for (var j = 0; j < this.selected.length; j++) {
if (this.selected[j].CODE === this.table1_data2[i].CODE) {
this.table1_data2[i]._checked = true;
}
}
}
},
最后在接口获取数据的地方调用updateChecked方法