el-table实现跨页多选、跨页全选、跨页禁用
背景:表格支持多选、表格外有全选按钮,用于选中所有数据,而非当前请求的10条20条
<template>
<el-button @click="selectAllData">
{{selectAllPage ? '取消全选' : '全选'}}
</el-button>
<el-table
@selection-change="selectionChange" // 当选择项发生变化时会触发该事件
@select-all="selectAll" // 当用户手动勾选全选 Checkbox 时触发的事件
rowKey="bid" // 跨页选中必须设置rowKey
ref="table"
>
<el-table-column
type="selection" // 添加复选框列
width="55"
reserve-selection // 保留跨页选中行
:selectable="selectable" // 通过回调配置当前行复选框是否禁用
>
...
</el-table-column>
</el-table>
</template>
<script>
data(){
return {
selectAllPage: false // 全选按钮状态
}
}
</script>
需求一
最多选80行,选中数据的id放入localStorage中;超出80行给出提示,并取消选中80个以后的数据
methods: {
selectionChange(data, status) {
if (data.length <= 80) {
if (data.length > 0) {
const obj = {
list: data.map((item) => item.bid)
};
localstorage.setItem('list',JSON.stringify(obj))
} else {
localStorage.removeItem("list")
}
} else {
this.$message.warning("超出可选择数量,多选最多选择80人");
// 获取第81个勾选的行,设置取消勾选
const delRow = data.pop();
this.$refs.table.toggleRowSelection([delRow], false);
}
}
}
需求二
点击表格内全选复选框,将数据存入localStorage
methods: {
selectAll(data) {
/*
每次点击全选都会触发 selectionChange,
所以不用顾忌点8页全选后与需求1冲突(最多选80人限制)
*/
// 解决 如果用户点击了全选按钮button,再次点击表格内全选复选框,导致给localstorage存储数据出错
if(this.selectAllPage) {
return
}
// 如果全选
if(data.length) {
const obj = {
list: data.map((item) => item.bid)
};
localStorage.setItem('list',JSON.stringify(obj))
}else{
// 取消全选
localStorage.removeItem("list")
}
}
}
需求三
点击表格外部的全选按钮,将筛选条件存入localStorage(不可能把所有数据的id存起来,数据量太大,筛选条件给后端,他们进行筛选)、所有数据全部选中(跨页)并且禁用复选框(跨页)、全选变成取消全选
methods: {
selectAllData(){
// 如果列表没数据,提示并退出方法
if(!this.table.data.length) {
this.$message.warning('暂无人员可选')
return false
}
// 切换全选状态
this.selectAllPage = !this.selectAllPage;
// 全选当前页数据
this.table.data.forEach(item=> {
// 遍历数据,切换全选全不选状态
this.$refs.table.toggleRowSelection(item, this.selectAllPage)
})
// 如果点击全选---按钮
if (this.selectAllPage) {
this.$nextTick(()=>{
// 每一行数据的禁用字段设置为true
this.table.data.forEach(item=> {
item.isDisable = true
})
})
// 存储筛选条件到localstorage
const obj = JSON.parse(JSON.stringify(this.search.params));
localStorage.setItem(JSON.stringify(obj));
} else {
// 取消全选--按钮
// 取消禁用
this.table.data.forEach(item=> {
item.isDisable = false
})
// 取消所有用户选中项
this.$refs.table.clearSelection()
}
}
}
额外配合需求的方法
获取表格数据、禁用行方法
methods: {
// 禁用方法
selectable(row) {
return row.isDisable === true ? false : true
},
// 获取表格数据
getTableData(){
// ...请求数据
this.table.data.forEach(item=>{
/*
初始化页面后,给每一行添加禁用属性,
否则页面挂载好后,点击全选按钮,无法将第一页数据禁用
*/
item.isDisable = false
})
// 此处处理用户点击外部全选button按钮,对第二页及以后的数据进行选中
this.$nextTick(()=> {
if(this.selectAllPage) {
this.table.data.forEach(item=> {
// 给每一行添加禁用属性
item.isDisable = true
this.$refs.table.toggleRowSelection(item,true)
})
}
})
}
}