二次封装el-select组件

1,265 阅读1分钟

就是把饿了么的el-select加了一个全选和反选的功能 talk is cheap,show me the code

<el-select v-model="selectedArray" multiple collapse-tags placeholder="请选择" @change="changeSelect" @remove-tag="removeTag">
    <el-option label="全选" value="all" @click.native="selectAll" />
    <el-option v-for="(item, index) in options" :key="index" :label="item.value" :value="item.value" />
 </el-select>

js部分

data() {
    return {
      selectedArray: [],
      options: [
        { value: '一一', label: 'one' },
        { value: '二二', label: 'tow' },
        { value: '三三', label: 'three' },
        { value: '四四', label: 'four' },
        { value: '五五', label: 'five' }
      ]
    }
  },
  methods: {
    selectAll() {
      if (this.selectedArray.length < this.options.length) {
        this.selectedArray = []
        this.options.map((item) => {
          this.selectedArray.push(item.value)
        })
        this.selectedArray.unshift('all')
      } else {
        this.selectedArray = []
      }
    },
    changeSelect(val) {
      if (!val.includes('all') && val.length === this.options.length) {
        this.selectedArray.unshift('all')
      } else if (val.includes('all') && (val.length - 1) < this.options.length) {
        this.selectedArray = this.selectedArray.filter((item) => {
          return item !== 'all'
        })
      }
    },
    removeTag(val) {
      if (val === 'all') {
        this.selectedArray = []
      }
    }
  }