方式一,彻底发挥了 vuejs 的特性,使用了 computed 实现了对 单选按钮的实时监控。vue
<div id="app"> <div class="box"> <div class="title"> <label><input type="checkbox" v-model="status">全选</label> </div> <ul> <li v-for="item,index of list"><label> <input type="checkbox" v-model="item.checked">{{item.title}}</label> </li> </ul> </div> </div> var list = [ { title : '数据一', checked : false, },{ title : '数据二', checked : true, },{ title : '数据三', checked : true, },{ title : '数据四', checked : true, },{ title : '数据五', checked : true, }]; var vm = new Vue({ el : '#app', data:{ list }, computed:{ status:{ get(){ return this.list.filter( item => item.checked ).length === this.list.length }, set( value ){ this.list.map(function( item ){ item.checked = value; return item; }); } } } });
方式二使用普通的事件监听方式处理数据状态app
<div id="app"> <div class="box"> <div class="title"><label> <input type="checkbox" v-model="status" @change="allCheck">全选</label></div> <ul> <li v-for="item,index of list"> <label><input type="checkbox" v-model="item.checked" @change="singleCheck">{{item.title}}</label></li> </ul> </div> </div> var list = [ { title : '数据一', checked : false, },{ title : '数据二', checked : true, },{ title : '数据三', checked : true, },{ title : '数据四', checked : true, },{ title : '数据五', checked : true, }]; var vm = new Vue({ el : '#app', data : { list, status : this.list.filter( item => item.checked ).length === this.list.length ? true : false }, methods : { allCheck(){ this.list.map(function( item ){ item.checked = this.status; return item; }.bind(this)); }, singleCheck(){ this.status = this.list.filter( item => item.checked ).length === this.list.length ? true : false } } });
说明在方式二中使用了事件监听函数,使用了change,也可使用 click,使用click事件时,低版本的vuejs存在 bug,高版本中 bug 修复,bug 存在于,在双向绑定状态改变时 使用click数据状态后滞后。函数