vue實現(xiàn)全選與反選
示例效果:
實現(xiàn)代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vue全選與反選</title>
<script src="./js/vue.js"></script>
</head>
<body>
<div id="my">
<input type="checkbox" v-model="checkAll.check" @change="checkAllChange()">
<label>{{checkAll.name}} {{checkAll.check}}</label>
<ul>
<li v-for="list in lists">
<input type="checkbox" v-model="list.check" @change="curChange()">
<label>{{list.name}} {{list.check}}</label>
</li>
</ul>
</div>
<script type="text/javascript">
window.onload = function () {
var app = new Vue({
el: "#my",
data: {
checkAll: { name: '全選', check: false },
lists: [{ name: '小米', check: true },
{ name: '華為1', check: false },
{ name: '華為2', check: false },
{ name: '華為3', check: false },
{ name: '華為4', check: false }]
},
//在methods這里面寫方法送膳、事件之類的
methods: {
checkAllChange: function () {
//使用箭頭函數(shù) this的作用域指當前實例化對象
this.lists.forEach(item => {
item.check = this.checkAll.check;
});
},
curChange:function(){
//過濾check為true的
var curTrue=this.lists.filter(function(item){
return item.check==true;
});
//判斷選中的狀態(tài)與總長度比較 當選中的項與總長度相等時 自動 勾選 “全選”
// 不相等時 取消 全選
if(curTrue.length==this.lists.length){
this.checkAll.check=true;
}else{
this.checkAll.check=false;
}
}
}
})
}
</script>
</body>
</html>