引入checkbox 组件
<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox> <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange"> <el-checkbox v-for="(city,i) in cities" :label="city.name" :key="i">{{city.name}}</el-checkbox> </el-checkbox-group> data(){ return { //全选 checkAll: false, cities: [ { "name":"高一", "value":"928" }, { "name":"高二", "value":"929" }, { "name":"高三", "value":"930" } ], //数据源 checkedCities:[], //绑定默认选中 isIndeterminate:false, //设置 indeterminate 状态,只负责样式控制 } methods:{ // 全选 --- 当绑定值变化时触发的事件 handleCheckAllChange(val) { console.log(val) //val的值是一个布尔值,点中全选为false,取消全选为true this.cities.forEach(item=>{ //当全选被选中的时候,循环遍历源数据,把数据的每一项加入到默认选中的数组去 this.checkedCities.push(item.name) }) this.checkedCities = val ? this.checkedCities : []; //三元表达式,如果val的值为true,那么就把当前默认选中的值赋值给自身,这样页面页面上所有的元素就都选中了。如果为false,就是取消全选 this.isIndeterminate = false; //官网说这是个样式控制,是来控制,什么时候半选的,要不要都无所谓,看你需求 }, // checkbox选中 --- 当绑定值变化时触发的事件 handleCheckedCitiesChange(value) { let checkedCount = value.length; //选中值的长度 this.checkAll = checkedCount === this.cities.length; //如果选中值的长度和源数据的长度一样,返回true,就表示你已经选中了全部checkbox,那么就把true赋值给this.checkAll this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length; //同全选按钮事件里面的那个样式控制 } },
api里面写的太麻烦了,写个易懂的如下:
<el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox> <el-checkbox v-for="(city,i) in cities" :label="city.name" :key="i" v-model="checkedCities" @change="handleCheckedCitiesChange">{{city.name}}</el-checkbox> handleCheckAllChange(val) {//val就是v-model绑定的值,即this.checkAll if(this.checkAll){ this.cities.forEach(item=>{ this.checkedCities.push(item.name) }) }else { this.checkedCities = [] } }, handleCheckedCitiesChange(value) {//value就是v-model绑定的值,即this.checkedCities console.log(this.checkedCities); if(this.checkedCities.length == this.cities.length){ this.checkAll=true }else{ this.checkAll=false } }