<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue复选框的全选</title>
</head>
<body>
<div id="app">
<!-- 全选 -->
<input type="checkbox" @click="checkAll()"><label>全选</label></br>
<!-- 单选 -->
<div v-for="item in sports">
<!--indexOf如果要检索的字符串值没有出现,则该方法返回 -1 -->
<input type="checkbox" :checked="sportsIds.indexOf(item.id)>-1" @click="checkOne(sports.id)" /><label>{{item.name}}</label>
</div>
</div>
<script src="jquery.min.js"></script>
<script src="vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
sports: [{
id: 1,
name: "打篮球"
},
{
id: 2,
name: "太极拳"
},
{
id: 3,
name: "乒乓球"
},
{
id: 4,
name: "踢足球"
},
{
id: 5,
name: "棒球"
}
],
sportsIds: [1, 3, 4],
isCheckAll: false
},
methods: {
checkAll: function() {
this.isCheckAll = !this.isCheckAll;
if (this.isCheckAll) {
this.sportsIds = []
for (var i = 0; i < this.sports.length; i++) {
this.sportsIds.push(this.sports[i].id);
}
} else {
this.sportsIds = []
}
console.log(this.sportsIds.length)
},
checkOne: function(sportsId) {
let idindex = this.sports.indexOf(sportsId);
if (idindex > 0) {
//如果以包含了该id,则去除(变为非选中状态)
this.sportsIds.splice(idindex, 1);
} else {
this.sportsIds.push(sportsId);
}
}
}
})
</script>
</body>
</html>