页面代码
//复选框部分
<div class="dataBlock"
v-for="(item,index) in tableData"
@touchmove="gtouchmove"
:key="index+'NoiceAlarm'">
<span :class=" CheckedIDS.indexOf(item.Id)>-1?'ivu-checkbox ivu-checkbox-checked':'ivu-checkbox'"
@click="handleClick(item.Id)"
v-show="isCheck">
<span class=" ivu-checkbox-inner">
</span>
<input type="checkbox"
class="ivu-checkbox-input">
</span>
<div>
//全选按钮部分
<span :class="isSelectAll?'ivu-checkbox ivu-checkbox-checked':'ivu-checkbox'"
@click="SelectAll()"
v-show="isCheck">
<span class=" ivu-checkbox-inner">
</span>
<input type="checkbox"
class="ivu-checkbox-input">
</span>
<div style="margin-left: 5px;font-size: 1rem;">全选</div>
</span>
js代码
data () {
return{
timeOutEvent: '',
isCheck: false,//是否显示复选框
CheckedIDS: [],//选中的Id
isSelectAll: false,//是否选中全部
}
}
handleClick(id) {
console.log(id)
let _index = this.CheckedIDS.indexOf(id)//判断当前id是否在CheckedIDS
if (_index > -1) {//在 =>删除
this.CheckedIDS.splice(_index, 1)
} else {//不在=>添加
this.CheckedIDS.push(id)
}
},
SelectAll () {
this.isSelectAll = !this.isSelectAll
if (this.isSelectAll) {//全选
this.CheckedIDS = []//先清空
this.tableData.forEach(item => {//再放入全部Id
this.CheckedIDS.push(item.Id)
})
} else {//取消全选
this.CheckedIDS = []
}
},
//长按事件
gtouchstart (e, ID) {
let that = this
that.timeOutEvent = setTimeout(function () {
that.longPress()//长按要执行的内容
}, 500)
return false;
},
//退出多选状态
CancelCheck () {//在0.5秒内释放
clearTimeout(this.timeOutEvent);//清除定时器
if (this.timeOutEvent != 0) {
this.isCheck = false
this.isSelectAll = false//取消全选状态
this.CheckedIDS = []//清空
this.tableData.forEach((item, index) => {
item.isChecked = false
})
} else {
this.isCheck = true
}
return false;
},
gtouchmove () {
clearTimeout(this.timeOutEvent);//清除定时器
this.timeOutEvent = 0;
},
//长按执行的内容
longPress () {
this.timeOutEvent = 0;
this.isCheck = true //显示多选框
},
css代码
.ivu-checkbox {
display: inline-block;
vertical-align: middle;
white-space: nowrap;
cursor: pointer;
line-height: 1;
position: relative;
}
.ivu-checkbox-inner {
display: inline-block;
width: 16px;
height: 16px;
position: relative;
top: 0;
left: 0;
border: 1px solid #dcdee2;
border-radius: 2px;
background-color: #fff;
transition: border-color 0.2s ease-in-out, background-color 0.2s ease-in-out,
box-shadow 0.2s ease-in-out;
}
.ivu-checkbox-checked .ivu-checkbox-inner {
border-color: #2d8cf0;
background-color: #2d8cf0;
}
.ivu-checkbox-input {
width: 100%;
height: 100%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 1;
cursor: pointer;
opacity: 0;
}
通过判断所点击的id是否在CheckedIDS中来判断当前checkbox的状态
而不是根据checkbox为选中状态将id放入CheckedIDS
通过id来判断的好处是数据的选中与取消是可控的,更加的简单