el-select 多选实现全选以及搜索可全选操作

刘乐童
2023-12-01

做这个也是因为测试反馈说一个一个选择实在是很头疼,顾做了次功能,不说啦,直接看代码吧。

1.下拉

  <el-form-item label="选择国家:" prop="site_id">
              <el-select
                v-model="formData.site_id"
                filterable
                clearable
                multiple
                collapse-tags
                placeholder="请选择"
                class="w-300"
                @change="changeSelectsite"
                :filter-method="filterChecksite"
              >
                <el-checkbox
                  v-model="checkedSite"
                  @change="selectAllsite"
                  style="margin-left: 230px; margin-bottom: 2px"
                  >全选</el-checkbox
                >
                <el-option
                  v-for="(item, key) in countrys"
                  :key="key"
                  :label="item.name"
                  :value="String(item.country)"
                ></el-option>
              </el-select>
            </el-form-item>

2.字段初始化

data(){
  return{
      //全选国家
      checkedSite: false,
      currentValsite: "",
      //国家
      countrys: [],
      countrysCopy: [],
      formData:{
        site_id: [],
      }
  }
}

3.获取下拉国家数据

      //国家  name country
      getCountryinfo().then((res) => {
        this.countrys = res.data;
        this.countrysCopy = res.data;
      });

4.实现全选方法

 //全选国家
    selectAllsite() {
      this.formData.site_id = [];
      if (this.checkedSite == true) {
        this.countrys.map((item) => {
          this.formData.site_id.push(item.country);
        });
      } else {
        this.formData.site_id = [];
      }
    },
    //选择
    changeSelectsite(val) {
      if (val.length == 0) {
        this.countrys = this.countrysCopy;
      }
      if (val.length === this.countrys.length) {
        this.checkedSite = true;
      } else {
        this.checkedSite = false;
      }
    },
    //模糊搜索
    filterChecksite(currentValsite) {
      if (currentValsite.length > 0) {
        let arr = [];
        this.formData.site_id.map((row) => {
          arr.push(...this.countrysCopy.filter((item) => item.country == row));
        });
        this.countrys = this.countrysCopy.filter((item) => {
          if (item.name.includes(currentValsite)) {
            return true;
          }
        });
        this.countrys.push(...arr);
        this.countrys = Array.from(new Set(this.countrys));
        this.currentValsite = currentValsite;
      } else {
        this.options = this.countrysCopy;
        this.currentValsite = "";
      }
    },
 类似资料: