业务要求表格翻页时,也要保持前一页所选状态,同时翻页时所有页全选,也不会覆盖掉之前取消选中的
**elementUI 表格添加reserveSelection选项 row-key添加 **
<TableList ref="table" :table-data="tableData":table-columns="tableColumns"
:reserveSelection="true" :is-selection="true" index
size="mini" :row-key="getRowKey" @selectionChange="handleSelectionChange" @selectChange="handleSelectChange"
@hook:mounted="addRowListener">
</TableList>
<el-button @click="AllCheck">{{!isCheckAll ? "所有页全选" : "取消所有页全选"}}</el-button>
data() {
return {
// 数据
tableData: [],
//存放取消的数据的key
cancelData: [],
//是否所有页全选
isCheckAll: false
};
},
methods: {
getRowKey(row) {
//row-key 的值
return row.invCode;
},
AllCheck() {
this.cancelData = []
this.isCheckAll = !this.isCheckAll;
this.$refs.table.$refs.tableList.clearSelection()
//所有页全选时当前先清空选择 然后全部选中
this.isCheckAll && this.$refs.table.$refs.tableList.toggleAllSelection()
},
// 选择项
handleSelectionChange(val) {
this.multipleSelection = val
},
//单选或全选
handleSelectChange(rows, row) {
//不是所有页全选 不用往下走
if (!this.isCheckAll) return
//单个选择时
if (row) {
// true就是选中,0或者false是取消选中
let selected = rows.length && rows.indexOf(row) !== -1
if (selected) {
//过滤到选中的
this.cancelData = this.cancelData.filter(item => item !== row.invCode)
} else {
//添加取消的
this.cancelData = [...new Set([...this.cancelData, row.invCode])]
}
} else {
//全选 那么全选中的数据肯定包含有当前表格数据的
let codeList = this.tableData.map(({ invCode }) => invCode);
let flag = rows.some(item => item.invCode == codeList[0])
// for (let i = 0; i < codeList.length; i++) {
// flag = rows.some(item=>item.invCode == codeList[i])
// }
//点击全选时 rows会是当前选中的数据 翻页选中的数据也在内
if (!flag) {
this.cancelData = [...new Set([...this.cancelData, ...codeList])]
} else {
//过滤到已经在全选选中的
this.cancelData = this.cancelData.filter(item => {
return !codeList.includes(item)
})
}
}
},
addRowListener() { },
/* 列表*/
getTableList(type) {
const params = {};
if (type == "rest") {
//搜索重置时 重置所有状态
this.cancelData = []
this.isCheckAll = false
this.$refs.table.$refs.tableList.clearSelection()
}
getList(params)
.then((res) => {
if (res.code === 0) {
const { totalCount, records } = res.data;
this.$set(this.paginationSetting, "total", totalCount || 0);
this.tableData = records || [];
//在搜索时和重置数据的时候清空状态
//全选下保持翻页已经取消选中的
if (this.isCheckAll) {
let codeList = this.tableData.filter(({ invCode }) => {
return !this.cancelData.includes(invCode)
})
this.$nextTick(() => {
codeList.forEach(row => {
//单个选中
this.$refs.table.$refs.tableList.toggleRowSelection(row, true)
})
})
}
}
})
.finally(() => {
this.fetchStatus = false;
});
},
},