vuejs实现checkbox全选和全不选
程序员文章站
2022-05-31 11:51:20
...
最近一直在用vue,有个功能是要实现全选和取消全选的功能,于是想了一下要怎么做。
效果如下:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue实现checkbox全选和全不选</title>
<script type="text/javascript" src="../lib/vue.min.js"></script>
<script type="text/javascript" src="../lib/jquery-1.11.3.min.js"></script>
<style>
#table {
width:600px;
height:200px;
margin:100px auto;
}
#table label{
padding:10px;
font-size:16px;
border:1px solid #ccc;
}
#table label input{
height:20px;
width:20px;
}
#table .active{
color:red;
}
</style>
</head>
<body>
<div id="table">
<p>
<label :class="check.length == ball.length ? 'active' : ''"><input type="checkbox" v-model="all.flag" @click.stop="allchoosed()">{{all.label}}</label>
</p>
<p>
<label v-for="(item, index) in ball"><input type="checkbox" v-model="check" :value="item.id" @click.stop="checkChoose()">{{item.label}}</label>
</p>
<h1>提交的id数组:{{check}}</h1>
</div>
</body>
</html>
<script>
var v = new Vue({
el: "#table",
data: {
check: [],
ball: [{
id: 1,
label: '篮球',
flag: false
},{
id: 2,
label: '足球',
flag: true
},{
id: 3,
label: '乒乓球',
flag: false
},{
id: 4,
label: '桌球',
flag: true
}],
all:{
flag: false,
label: '全选'
}
},
methods: {
checkChoose: function() {
var _this = this;
_this.all.flag = (_this.check.length == _this.ball.length) ? true : false;
_this.all.label = (_this.check.length == _this.ball.length) ? '取消全选' : '全选';
},
allchoosed: function(){
var _this = this;
if(_this.all.flag){
_this.check = [];
_this.ball.forEach(function(item, index){
_this.check.push(item.id);
});
_this.all.flage = true;
_this.all.label = '取消全选';
}else{
_this.ball.forEach(function(item, index){
_this.check = [];
});
_this.all.flage = false;
_this.all.label = '全选';
}
}
},
created: function(){
var _this = this;
var flag = true;
//载入时判断是否为全选状态
_this.ball.forEach(function(item, indx){
if(item.flag){
_this.check.push(item.id);
}
});
_this.all.flag = (_this.check.length == _this.ball.length) ? true : false;
_this.all.label = (_this.check.length == _this.ball.length) ? '取消全选' : '全选';
}
});
</script>