首先要用到el-table的以下两个事件,以及一个勾选项的空数组:
- @select:当用户手动勾选数据行的 Checkbox 时触发的事件。
- @select-all:当用户手动勾选全选 Checkbox 时触发的事件。
- const selectListAll = [ ]
select-all的使用:
- 假定我当前select-all定义的方法为handleSelectAll,那么当前这个方法接收的参数selection,就是当前页是否全选的数据。
- 当selection的length为0的时候,就是取消全选。
- 当selection的length大于0的时候,就是全选。
- 全选的时候,使用map方法将selection和selectListAll,去重展开在selectListAll中。
- 取消全选的时候将selection从selectListAll中剔除。
// 定义变量保存勾选的数据
const selectListAll = ref([]); // 当前勾选的选项
const handleSelectAll = (selection) => {
if (selection.length > 0) {
console.log('全选', selection);
selectListAll.value = [...new Map([...selectListAll.value.map((item) => [item.id, item]), ...selection.map((item) => [item.id, item])]).values()];
}
if (selection.length === 0) {
console.log('取消全选', selection);
selectListAll.value = selectListAll.value.filter((item) => !state.tableData.data.some((d) => d.id === item.id));
}
};
select的使用:
- 假定我当前select定义的方法为handleSelect,那么handleSelect接收两个参数,selection为当前页已经选中的数据,row为当前操作的数据。
- 当selection中包含row,表示是勾选状态。
- 当selection中不包含row。表示为取消勾选。
- 为勾选状态时,将这一条数据添加到selectListAll勾选项数组中。
- 为取消勾选状态时,将这一条数据从selectListAll中剔除。
const handleSelect = (selection, row) => {
if (selection.some((item) => item.id === row.id)) {
console.log('勾选的行:', row);
selectListAll.value.push(row);
} else {
// 取消勾选操作,移除 id
console.log('取消勾选的行:', row);
selectListAll.value = selectListAll.value.filter((item) => item.id !== row.id);
}
};
翻页时的逻辑:
- 当出发分页方法时,调用接口获取数据,获取数据后,在nextTick中使用toggleRowSelection方法来渲染已经勾选的项。
- res.data是我请求来的数据。循环selectListAll,判断请求来的数据中包含selectListAll的数据,那么当前这一项就是要勾选的。
- tableRef是当前el-table的ref,因为要使用toggleRowSelection方法,所以要指定到具体的el-table
nextTick(() => {
selectListAll.value.forEach((selected) => {
const row = res.data.find((item) => item.id === selected.id);
if (row) {
tableRef.value?.toggleRowSelection(row, true);
}
});
});
提示:我在接收数据的地方,selectListAll做了去重处理。如果以上逻辑不是在组件中,建议在nextTick中为selectListAll做去重处理。
633

被折叠的 条评论
为什么被折叠?



