element ui el-select下拉多选添加全选功能

发布时间 2023-12-14 15:53:12作者: Jerrycoco
// html
      <div class="item" >
        <span class="label">观测要素</span>
        <span>
          <!-- 要素组批量处理-多选 -->
          <el-select  v-model="eleTypeList" multiple @change="eleTypeChangeList" class="theme-select" style="width: 1430px;" placeholder="请选择">
            <el-option label="全选" value="selectAll"  v-if="ElementTypebyOption.length > 0"></el-option>
            <el-option v-for="(item, index) in ElementTypebyOption" :key="index" :label="item.TEXT" :value="item.ID"></el-option>
          </el-select>
        </span>
      </div>
// data
      ElementTypebyOption: [],
      oldSeleValue: [],
      eleTypeList: [],
      elementTypeList: [],
//methods中
// 观测要素批量下拉列表
    getObsvItem (flag = false) {
      let params = {
        stationType: this.staType,
        dataType: this.dataType,
        eleType: ''
      }
      this.ElementTypebyOption = []
      this.eleTypeList = []
      WORK_API.getObsvItem(params).then(res => {
        this.ElementTypebyOption = res.data
        if (this.ElementTypebyOption.length !== 0) {
          this.ElementTypebyOption.forEach((item, index) => {
            this.eleTypeList.push(item.ID)
          })
        }
        this.eleTypeList.push('selectAll');
        this.$nextTick(() => {
          // 获取el-tag--info类名的元素
          var dom = document.getElementsByClassName('el-tag--info')[0]
          const content = dom.innerText;
          if (content == 'selectAll') {
            dom.style.display = 'none'; // 隐藏选择的元素
          }
          setInterval(() => {
            this.eleTypeChangeList(this.eleTypeList)
          }, 200)
        })
        console.log(this.eleTypeList)
      }).catch(err => {
        console.log(err)
      })
    },
eleTypeChangeList(val) {
      // 用来储存上一次的值,可以进行对比
      const oldVal = this.oldSeleValue.length === 1 ? this.oldSeleValue[0] : [];
      // 若是全部选择
      if (val.includes('selectAll')) {
        this.eleTypeList = Object.assign([],this.allSeleValue);
        this.eleTypeList.push('selectAll');
      }
      // 取消全部选中 上次有 当前没有 表示取消全选
      if (oldVal.includes('selectAll') && !val.includes('selectAll')) this.eleTypeList = [];
      // 点击非全部选中 需要排除全部选中 以及 当前点击的选项
      // 新老数据都有全部选中
      if (oldVal.includes('selectAll') && val.includes('selectAll')) {
          const index = val.indexOf('selectAll');
          val.splice(index, 1); // 排除全选选项
          this.eleTypeList = val
      }
 
      // 全选未选 但是其他选项全部选上 则全选选上 上次和当前 都没有全选
      if (!oldVal.includes('selectAll') && !val.includes('selectAll')) {
          if (val.length ===  this.allSeleValue.length) {
            this.eleTypeList.push('selectAll');
          };
      }
      // 储存当前最后的结果 作为下次的老数据
      this.oldSeleValue[0] = this.eleTypeList;
    },