1、用到的方法
- select-all 当用户手动勾选全选 Checkbox 时触发的事件 selection
- select 当用户手动勾选数据行的 Checkbox 时触发的事件 selection, row
<el-table
ref="crud"
:data="data"
tooltip-effect="dark"
style="width: 100%"
@select="selectRow"
@select-all="selectAll"
></el-table>
2、data中定义字段用于存放全量已选择ID
用于回显及保存,初始化从接口获取(本例数据格式为字符串,多个以逗号分割): "xxxx,xxxx,xxxx"
data(){
return {
data:[], // 表格数据
selectIdList: [], // 已选择的行数据id列表
}
}
mounted(){
getList(){
// 请求接口获取selectIdList初始化内容,用于反显(这里默认接口返回的是字符串,以逗号分割)
this.selectIdList = res.data.split(',')
}
}
3、数据回显、单选、全选方法
// 数据回显
selectedRecords(){
if(Array.isArray(this.data)){
setTimeout(()=>{
const selections = this.data.filter(item => {
const selected = this.selectedIdList.includes(item.id)
return selected;
})
if(selections.length == 0) {
return;
}
// 回显
this.$refs.crud.toggleSelection(selections);
},50)
}
},
// 全选
selectAll(list){
// list为空,表示全不选
if(list.length == 0){
// 将当前页表格的数据循环判断是否存在在selectedIdList中,存在就删除
this.data.map((item,index)=> {
const isExistListAll = this.selectedIdList.indexOf(item.id);
if(isExistListAll != -1){
this.selectedIdList.splice(isExistListAll,1);
}
})
} else {
// 循环list,将不存在的值加上
list.map((item,index)=> {
if(this.selectedIdList.indexOf(item.id) == -1){
this.selectedIdList.push(item.id)
}
})
}
},
// 单选
selectRow(list, row){
const rowId = row.id;
// 是否存在于selectedIdList, -1表示不存在
let isExistList = this.selectedIdList.indexOf(rowId);
// row.id不存在在list中的时候,说明是取消勾选,undefined表示去除勾选
if(list.find(item=>{return item.id == rowId}) == undefined) {
// 去除,判断在selectedIdList是否存在,存在就删除
if(isExistList != -1){
this.selectedIdList.splice(isExistList, 1);
}
} else {
// 添加
if(sExistList == -1){
this.selectedIdList.push(rowId)
}
}
}
// 获取表格数据
getTable(){
...
// 获取完表格数据后调用回显
this.selectedRecords()
}
// 勾选的数据,提交报存的时候根据需求传递
this.selectedIdList