其他分享
首页 > 其他分享> > 关于element中checkbox组件三种状态实现的详解

关于element中checkbox组件三种状态实现的详解

作者:互联网

1. checkbox三种状态

checkbox有三种状态全选(显示'√'),选中部分(显示的-'),全不选(啥都没显示)

对于indeterminate和v-model绑定的值(均为boolean类型):

① 如果 true true 或者 true false 样式为-

② 如果 false true 样式为√

③ 如果 false false 样式为不勾

 2. element源码解析

isIndeterminate属性,为boolean类型,绑定isIndeterminate变量,默认值为true
用于确定是否为不确定状态,true为不是全选,false为全选或全不选

v-model绑定变量checkAll,为boolean类型,默认值为false
用于控制是否全选,true为全选,false为不全选

<template>
  <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
  <!-- change事件, 当绑定值变化时触发, 回调参数为更新后的值 -->
  <div style="margin: 15px 0;"></div>
  <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
    <el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox>
  </el-checkbox-group>
</template>
<script>
  const cityOptions = ['上海', '北京', '广州', '深圳'];
  export default {
    data() {
      return {
        checkAll: false,
        checkedCities: ['上海', '北京'],
        cities: cityOptions,
        isIndeterminate: true
      };
    },
    methods: {
      handleCheckAllChange(val) {
        //处理点击全选框事件

        this.checkedCities = val ? cityOptions : [];
        //选中时val为true, this.checkedCities = cityOptions = ['上海', '北京', '广州', '深圳'] , 即全选
        //未选中时val为false, this.checkedCities = [], 即全不选
        
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        //处理点击选中元素框事件, 回调选中的所有元素的值存入value

        let checkedCount = value.length;  
        //将选中元素的数量存入checkedCount

        this.checkAll = checkedCount === this.cities.length;
        //this.cities = cityOptions = ['上海', '北京', '广州', '深圳'] 
        //--> 判断是否全选

        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
        //--> 判断是否不全选, 也即判断是否为'-'
      }
    }
  };
</script>

标签:checkbox,false,isIndeterminate,checkedCount,element,cityOptions,全选,true,详解
来源: https://blog.csdn.net/CH_whale/article/details/121266997