全选下拉框组件

69 阅读1分钟
<template>
  <!-- 全选下拉框组件 -->
  <el-select
    placeholder="请选择"
    filterable
    multiple
    collapse-tags
    value-key="key"
    size="medium"
    style="width: 100%"
    v-model="selectValue"
    :clearable="clearable"
    @clear="clear"
    @change="change"
  >
    <li
      class="el-select-dropdown__item"
      :class="{ selected: SelectedAll }"
      @click="onSelectedAll"
    >
      <span>全选</span>
    </li>
    <el-option
      :label="item[label]"
      :value="item[valueKey]"
      :key="key"
      v-for="(item, key) in List"
    >
    </el-option>
  </el-select>
</template>
<script>
export default {
  props: {
    //显示label
    label: {
      type: String,
      default: "label",
    },
    //取值
    valueKey: {
      type: String,
      default: "value",
    },
    value: {
      type: Array,
      default: () => [],
    },
    //是否显示清除按钮
    clearable: {
      type: Boolean,
      default: false,
    },
    //下拉数据
    List: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      selectValue: [],
    };
  },
  computed: {
    // 全选的勾选状态 true、false
    SelectedAll() {
      return this.selectValue.length === this.List.length;
    },
  },
  watch: {
    value(newVal) {
      this.selectValue = newVal;
    },
    selectValue(newVal) {
      this.$emit("input", newVal);
    },
  },
  methods: {
    clear() {
      this.$emit("clear");
    },
    change(e) {
      this.$emit("change", e);
    },
    onSelectedAll() {
      if (this.SelectedAll) {
        // 取消全选
        this.selectValue = [];
      } else {
        this.selectValue = this.List.map((item) => item[this.valueKey]);
      }
    },
  },
};
</script>
//使用
<all-select
              v-model="value"
              :List.sync="List"    
              :label="'label'"
              :valueKey="'valueKey'"
              @input="input"
              clearable
            ></all-select>