vue elementui 结合 el-checkbox-group 组件实现全选效果

发布于:2024-04-28 ⋅ 阅读:(29) ⋅ 点赞:(0)

结合 el-checkbox-group 组件实现全选效果,效果图在文章末尾

直接上代码

<template>
  <div>
    <div style="display: flex;height: 27px;border-radius: 5px;">
      <div v-for="(item, idx) in legendClickList" :key="idx" style="width: 55px;height: 27px;padding-top: 4px;">
        <div style="transform: scale(0.8);text-align: center;color:rgb(68,67,67);font-weight: 700;">{{item.value}}</div>
      </div>
    </div>
    <el-checkbox-group style="" v-model="checkboxGroup" size="mini" @change="changeCheckboxGroup">
      <el-checkbox-button v-for="(item, idx) in legendClickList" :label="item.name" :key="idx">
        <div>{{item.name}}</div>
      </el-checkbox-button>
    </el-checkbox-group>
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  props: {},
  data () {
    return {
      checkboxGroup:['全部'],
      isTotal: '全部',
      legendClickList: [
        {
          name: '全部',
          value: '',
        },
        {
          name: '上海',
          value: '50%',
        },
        {
          name: '北京',
          value: '20%',
        },
        {
          name: '广州',
          value: '10%',
        },
        {
          name: '深圳',
          value: '20%',
        },
        {
          name: '厦门',
          value: '20%',
        },

      ],
      categories: [],
    }
  },
  created () {},
  mounted () {},
  computed: {},
  watch: {},
  methods: {
    changeCheckboxGroup () {
      let isTotal = this.isTotal;
      let len = this.checkboxGroup.length
      let totalLen = this.legendClickList.length;
      if (len < 1 || len === totalLen) {
        // 都不选 或者都选择了 那么就设置为 全部
        this.checkboxGroup = [isTotal]
      } else {
        // 最后一个也就是新增的是 全部 ,那么设置为 全部
        if (this.checkboxGroup[len - 1] == isTotal ) {
          this.checkboxGroup = [isTotal]
        } else {
          // 那么除去新增的之外,已有的里面包含 全部 时候,需要去掉
          if (this.checkboxGroup.includes(isTotal)) {
            let temp = this.checkboxGroup.filter((item) => {
              return item != isTotal
            })
            this.checkboxGroup = temp;
          } else {
            // 当除了 全部 其他类型全部选择的时候 可以设置为全部
            // if(len == totalLen -1){
            //   this.checkboxGroup = [isTotal];
            // }
          }
        } 
      }

      if(this.checkboxGroup.includes(isTotal)) {
        this.categories = ['上海','北京','广州','深圳','厦门']
      } else {
        this.categories = this.checkboxGroup
      }

      console.log(this.checkboxGroup,'this.checkboxGroup-----');
      console.log(this.categories,'this.categories-----');
    },
  },
}
</script>

<style lang="scss" scoped>
  
</style>

效果图:

在这里插入图片描述