结构描述:前端+后端+UI为一个独立的el-checkbox-group;

选项一+选项二为一个独立的el-checkbox-group;

两个独立的group处于一个大el-checkbox中;

实现目标:1.任意一个复选框的状态需要与全选框联动;

2.点击选项二后选项一被联动取消,在两个都被勾选的情况下取消选项一时选项二也被联动取消

示例代码:

<template>
  <div>
    <el-checkbox
      :indeterminate="isIndeterminate"
      v-model="checkAll"
      @change="handleCheckAllChange"
      >全选</el-checkbox
    >
    <!-- MainChecked -->
    <!-- 定义第一个checkbox-grop, -->
    <el-checkbox-group
      v-model="MainChecked"
      @change="handleCheckedCitiesChange"
    >
      <el-checkbox v-for="obj in MainList" :label="obj.val" :key="obj.val">{{
        obj.name
      }}</el-checkbox>
    </el-checkbox-group>
    <!-- OtherChecked -->
    <el-checkbox-group v-model="OtherChecked">
      <el-checkbox
        v-for="obj in OtherList"
        :label="obj.val"
        :key="obj.val"
        @change="linkage(obj.val)"
        >{{ obj.name }}</el-checkbox
      >
    </el-checkbox-group>
  </div>
</template>

<script>
export default {
  name: '',
  data () {
    return {
      checkAll: false,
      MainChecked: [],
      OtherChecked: [],
      MainList: [
        { name: '前端', val: 'qianduan' },
        { name: '后端', val: 'houduuan' },
        { name: 'UI', val: 'ui' }
      ],
      OtherList: [
        { name: '选项一', val: 'option1' },
        { name: '选项二', val: 'option2' }
      ],
      isIndeterminate: false,
      // 这里一定要将首次点击的初始值作为第一个,否则首次将无法选中第一个参数
      linkageval: 'option1'
    }
  },
  created () {},
  watch: {
    //  监听用户的点击项,当linkageval值发生改变的是执行代码
    linkageval () {
      if (this.linkageval === 'option2' && this.OtherChecked.length === 1) {
        this.OtherChecked = ['option1', 'option2']
      }
      if (this.linkageval === 'option1' && this.OtherChecked.length === 1) {
        this.OtherChecked = []
      }
    //  由于OtherList无法参与MainList的点击事件,这里可以手动调用方法计算个数
      this.handleCheckedCitiesChange()
    }
  },
  methods: {
    //  记录用户的点击项,当点击项发生改变时触发方法修改全选状态
    linkage (val) {
      this.linkageval = val
      this.handleCheckedCitiesChange()
    },
    handleCheckAllChange (val) {
      this.isIndeterminate = false
      // 触发了全选按钮,如果选中为true就返回所有内容,否则返回空数组
      this.checkAll = val
      this.MainChecked = val ? this.MainList.map(item => item.val) : []
      this.OtherChecked = val ? ['option1', 'option2'] : []
      // 如果全选中或全未选都取消-横杠样式
    },
    handleCheckedCitiesChange () {
      // 触发了单个按钮,如果选中按钮数>0且<按钮总数则显示isIndeterminate样式
      let allCount = this.MainList.length + this.OtherList.length
      let checkCount = this.MainChecked.length + this.OtherChecked.length
      //   console.log(this.MainChecked, this.OtherChecked, 'checkCount', 111111)
      this.isIndeterminate =
        checkCount > 0 && checkCount < allCount ? true : false
      // 如果选中个数=总数,则全选框状态为选中
      this.checkAll = allCount === checkCount ? true : false
    }
  }
}
</script>

Logo

前往低代码交流专区

更多推荐