el-table中单击选中单元格,再次点击可取消选中,并支持多选
这次的需求中还要求单击选中单元格,再次点击可取消选中,并且支持多选
其中用到的数据结构同上一篇文章一致,我就不在贴代码了
博客园地址:https://www.cnblogs.com/bingchenzhilu/p/16827461.html
<el-table v-loading="loading" :data="assistlist.lists" @cell-click="goclick" @cell-dblclick='handleMouseEnter' row-style="{height: '0'}" :cell-style="myclass" :cell-class-name="cellClassName" >
</el-table>
上边是我删除了表格内部的数据,只留了表格结构的代码
我标蓝的是执行的方法
goclick(row,column,event,cell) {
let that=this
let isdel=false
let obj={
row:row.index,
column:column.index
}
console.log(that.checkArr);//checkArr是选中的单元格的横纵坐标键值对:形式如[{row:'',column:''}]
if(obj.column!=0){
console.log(that.checkArr);
that.checkArr.forEach((val,index)=>{
if(val.column==obj.column&&val.row==obj.row){
isdel=true//我在组装数组的时候,发现数据拼接错误,所以需要先遍历一遍,当前点击的是否在数组中已经存在
}
})
if(that.checkArr.length==0){
that.checkArr.push(obj)
}else{
try{
that.checkArr.forEach((val,index)=>{
if(isdel){
if(val.column==obj.column&&val.row==obj.row){
console.log('删除');
that.checkArr.splice(index,1)//如果已经存在,即可删除;即可满足再次点击可取消选中的需求
}
}else{
if(val.row==obj.row&&val.column!==obj.column){
console.log('push1');
that.checkArr.push(obj)
throw Error();
}else if(val.column==obj.column&&val.row!==obj.row){
console.log('push2');
that.checkArr.push(obj)
throw Error();
}else if(val.column!==obj.column&&val.row!==obj.row){
console.log('push3');
that.checkArr.push(obj)
throw Error();
}
}
})
}catch(e){
console.log(e)
}
}
}
},
我这里使用try catch是为了当二维数组每次比对不相等时,会进入下一次循环,从而导致一次点击,多次push的原因,因此,使用try catch跳出此次循环
现在选中数组有了,怎样进行展示呢
myclass(row){
console.log(this.checkArr);
for(var i=0;i<this.checkArr.length;i++){
if(row.columnIndex==this.checkArr[i].column&&row.rowIndex==this.checkArr[i].row){
return 'background:#DFEEFE;border:1px solid #5E99FD;';
}
}
},
cellClassName({row, column, rowIndex, columnIndex}){
row.index = rowIndex;
column.index = columnIndex;
},
下边的是这次代码的效果,我录了一个屏(原谅我没找到在博客园上传视频的方法)
以下是视频链接:https://f.video.weibocdn.com/o0/Eez5aqNjlx080hzCs3hK010412000F120E010.mp4?label=mp4_720p&template=1788x720.25.0&media_id=4828781500891257&tp=8x8A3El:YTkl0eM8&us=0&ori=1&bf=4&ot=h&lp=1605BOUQexKr7wn9pMFPh6&ps=mZ6WB&uid=6h4evL&ab=8224-g0,7397-g1,8143-g0,3601-g31,8013-g0,7598-g1&Expires=1666758405&ssig=P9iFV%2BAlT8&KID=unistore,video
cell-style可以指定显示特定条件下的单元格。
我的代码只是实现以上需求,可能实用性包括简洁性不够,多多包涵

浙公网安备 33010602011771号