select组件和checkbox组件组合使用

由于业务的需要,当数据量多的时候,select组件没办法快速的去掉默认的选项,选择一个未选中选项,思索了好久,突然想到可以把select组件和checkbox组件组合使用,就可以达到目的了,先看效果:
在这里插入图片描述
为了更通用和复用性更高,我把select和checkbox封装成了一个新的组件select-checkbox-group,核心代码如下:

<template>
  <div>
    <el-popover
      :width="popoverWidth"
      trigger="click">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
        全选
      </el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="selectCheckboxGroupValue" @change="handleCheckedChange">
        <el-checkbox v-for="item in list" :label="item.value" :key="item.value" :style="`width: ${checkboxWidth}px`">
          {{item.label}}
        </el-checkbox>
      </el-checkbox-group>
      <el-select
        slot="reference"
        v-model="selectCheckboxGroupValue"
        multiple
        collapse-tags
        placeholder="请选择">
        <el-option
          class="el-option"
          v-for="item in list"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </el-popover>
  </div>
</template>
<script>

export default {
  name: 'select_checkbox_group',
  props: {
    value: {
      type: Array,
      default () {
        return []
      }
    },
    list: {
      type: Array,
      default () {
        return []
      }
    },
    popoverWidth: {
      type: Number,
      default: 570
    },
    checkboxWidth: {
      type: Number,
      default: 150
    },
  },
  data () {
    return {
      selectCheckboxGroupValue: this.value,
      checkAll: this.value.length === this.list.length,
      isIndeterminate: this.value.length > 0 && this.value.length < this.list.length,
    }
  },
  watch: {
    selectCheckboxGroupValue: {
      handler: function (n, o) {
        this.$emit('input', n);
      }
    }
  },
  methods: {
    //全选
    handleCheckAllChange (val) {
      if (val) {
        let arr = []
        this.list.forEach(item => {
          arr.push(item.value)
        })
        this.selectCheckboxGroupValue = arr
      } else {
        this.selectCheckboxGroupValue = []
      }
      this.isIndeterminate = false;
    },

    // 一个个选
    handleCheckedChange (value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.list.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.list.length;
    },
  },
}
</script>
<style lang="less" scoped>
.el-option {
  display: none
}
</style>

在使用这个组件的时候,只需要传入原始select组件的v-model和v-for即可

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页