效果:
可直接运行,默认用的当前数据(get请求接口返回数据就可以用)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 表单全选功能</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
</head>
<body>
<div id="app">
<table class="table table-striped">
<caption><h1>列表</h1></caption>
<thead>
<tr>
<th><input type="checkbox" v-model="checkAll" @change="checkboxAll" >全选</th>
<th>名称</th>
<th>城市</th>
<th>邮编</th>
</tr>
</thead>
<tbody>
<tr v-for="item in lists">
<td> <input type="checkbox" value="" v-model="item.check" @change="changeCur"></td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.age}}</td>
</tr>
</tbody>
</table>
<button @click="send">点击获取后台数据</button>
</div>
<style>
#app {width:800px; margin:0 auto ; }
</style>
<script type = "text/javascript">
new Vue({
el: '#app',
data: {
checkAll:false,
lists: [
{name:'数据1',age:'12',check:true},
{name:'数据2',age:'15',check:false},
{name:'数据3',age:'13',check:true},
{name:'数据4',age:'11',check:true}
],
},
methods: {
send:function(){
//发送get请求
this.$http.get('post.php',{params : {num:10,b:2}}).then(function(res){
this.lists=res.body.lists;
},function(){
console.log('请求失败处理');
});
},
checkboxAll:function(){
/*for(var i=0;i< this.lists.length;i++){
this.lists[i].check = this.checkAll; //第一种方法
}*/
//第二种方法 用forEach
this.lists.forEach(item=>{
item.check = this.checkAll
});
},
changeCur:function(){//当前选项
//console.log(this.lists.length);
/*var n= this.lists.length;
let cur = this.lists.filter(function(item,index){ //筛选打勾的 filter()对数组进行筛选,返回满足条件的数组
return item.check==true;
}).length;
n==cur ? this.checkAll=true :this.checkAll=false ; /三目运算
*/
//代码优化
this.checkAll = this.lists.every(function(item){ return item.check});
}
},
mounted:function(){
//this.send(); //挂载完成的时候加载
}
})
</script>
</body>
</html>