vue2 el-table跨分页多选以及多选回显
个人博客 | snows_l.s BLIOGhttp://snows-l.site
一、多选
1、特别注意的属性以及方法:
:row-key="(_) => _.mac"
:reserve-selection="true"
@select="handleSelectionChange"
@select-all="handleSelectionChangeAll"
详情以及使用方法位置请查看代码
2、代码:
1)、template
<el-table
ref="multipleTable"
v-loading="loading"
:data="terminalList"
@select="handleSelectionChange"
@select-all="handleSelectionChangeAll"
:row-key="(_) => _.mac"
>
<el-table-column
type="selection"
align="center"
:reserve-selection="true"
width="55"
/>
// 其他列...
</el-table>
2)、js
data() {
return {
ids:[], // 用于维护选中的id集合
}
},
methods: {
// 多选框选中数据
handleSelectionChange(selection, row) {
let selectRow = selection.filter((item) => {
return item.mac == row.mac;
});
// 选中
if (selectRow.length) {
if (!this.ids.includes(row.mac)) {
this.ids.push(row.mac);
}
} else {
// 取消选中
if (this.ids.includes(row.mac)) {
this.ids.splice(this.ids.indexOf(row.mac), 1);
}
}
this.single = selection.length !== 1;
this.multiple = !selection.length;
},
// 全选按钮选中数据
handleSelectionChangeAll(selection) {
if (selection.length) {
// 全选
selection.forEach((item) => {
if (!this.ids.includes(item.mac)) {
this.ids.push(item.mac);
}
});
} else {
// 取消全选
this.terminalList.forEach((item) => {
if (this.ids.includes(item.mac)) {
this.ids.splice(this.ids.indexOf(item.mac), 1);
}
});
}
this.single = selection.length !== 1;
this.multiple = !selection.length;
},
}
二、多选回显
1、关键方法
// 用于清空选中的
this.$refs["multipleTable"].clearSelection();
// 用于回显选中
this.$refs["multipleTable"].toggleRowSelection(item, true);
2、实现
1)、首先的把绑定的值带回来
2)、然后再每次调接口, 也就是当前页中进行处理就好了(翻页/查询/重置,只要每次调接口)
3)代码如下
// 回显table数据的方法
handleSelectTable() {
// 首先清空当前页的勾选
this.$refs["multipleTable"].clearSelection();
// 再当前页中找到回显勾选的行 terminalList 是绑定的table数据
let arr = this.terminalList.filter((item) => {
return this.ids.includes(item.mac);
});
// 循环勾选
arr.forEach((item) => {
this.$refs["multipleTable"].toggleRowSelection(item, true);
});
},
/** 查询终端列表 */
getList() {
this.loading = true;
listTerminal(this.queryParams)
.then((response) => {
this.terminalList = response.rows;
this.total = response.total;
this.handleSelectTable(); // 每次都调用接口(分页/重置查询),都去重置当前页的选中状态
})
.finally(() => {
this.loading = false;
});
},