首先,需要在data里面定义一个我们勾选的数组,GovXuanList:[]。
事件,1、勾选单个数据事件。2、全选 / 取消全选事件。3、切换页事件。
1、勾选单个数据时,判断当前勾选的数据是选中的,还是取消选中的。如果是选中的,则放入GovXuanList数组中,如果是取消选中的,则从GovXuanList中删除。具体代码如下:
// 勾选单个数据
select(selection, row) {
//selection 为当前页已勾选的数组;row为当前操作的某一行数据
// 判断是否勾选
let checkedTrue = selection.length && selection.indexOf(row) !== -1;
if (!checkedTrue) {
// 取消勾选,使用filter()方法过滤掉刚刚勾选的那一条数据
this.GovXuanList = this.GovXuanList.filter(
(item) => item.uuid != row.uuid
);
}
if (checkedTrue) {
// 勾选,将刚刚勾选的数据用push()方法放进数组
this.GovXuanList.push(row);
}
},
2、全选 / 取消全选事件。全选时将本页面所有(可以勾选的)数据放入GovXuanList数组中,取消全选时,将本页面所有(可以勾选的)数据从GovXuanList中过滤掉。具体代码如下:
// 全选
selectAll(selection) {
// selection 为当前页面的勾选数组
if (selection.length > 0) {
// 全选,将本页面所有(可以勾选的)数据放入自定义的勾选数组里
this.GovXuanList.push(...selection);
} else {
// 取消全选,将本页面所有(可以勾选的)数据用filter()+every()方法过滤掉
this.GovXuanList = this.GovXuanList.filter(
(item) => this.nowTableData.every((it) => it.uuid != item.uuid)
// every方法,数组里面所有数据为真则返回真
);
}
},
3、切换页,表格数据数据变化时。此时要做的就是,当数据更新时,要将本页面的数据与已勾选的数组进行一个比较GovXuanList,得到本页面已经勾选的数据,进行一个回显操作。具体代码如下:
// 表格数据变化后的操作
getNowTableData(datayayaya) {
// 由于表格组件是封装的,所以这里有一个回调函数吐出当前的表格数据
// 也可以直接在获取表格数据的方法后面直接写
this.nowTableData = datayayaya; // 当前页的表格数据
// arr就是当前页的数据与已勾选的数据比较过滤之后得到的,当前页面已勾选的数组
const arr = datayayaya.filter(
(item) => this.GovXuanList.some((it) => it.uuid === item.uuid)
// some()方法,数组里有一个为真则返回真
);
this.$nextTick(() => {
// 要用nextTick(()={})去更新页面
arr.forEach((row) => {
// 将数据进行回显
this.$refs.table.$refs.multipleTable.toggleRowSelection(row, true);
});
});
},