vue el-select 加全选事件

165 阅读1分钟

html

  <el-select v-model="value" multiple size="mini" ref="myselect" collapse-tags placeholder="请选择" @change="handleChangeCenter($event,options)">
    <el-option  label='全选' value='全选'> </el-option>
    <el-option v-for="item in options" :key="item.value :label="item.label" :value="item.value"> </el-option>
</el-select>

change改变事件

handleChangeCenter(val,options) {
  let selectRef = this.$refs.myselect;//这个是为了获取当点击全部选中之后,再点全选的时候,取消所有,获取当前的label或value
  this.value = allChoiceChange(val,options,selectRef)
}, 

引入方法 import {allChoiceChange } from './../../../utils/verification'

verfication.js

export function allChoiceChange(val,options,selectRef) {
    var end = val[val.length - 1];
    // console.log('0000',selectRef.selected[0].label)
    // console.log("111===", this.value, val);
    if (!val.includes("全选") && val.length === options.length) {
      val.unshift("全选");
      if(selectRef !=undefined) {
        console.log('全的的')
        if(selectRef.selected[0].label == '全选') {
          val = [];
        }
      }
    //   console.log("222===", this.value, val);
    } else if (val.includes("全选") && val.length == 1) {
      options.map(item => {
        val.push(item.value);
      });
    //   console.log("333===", this.value, val);
    } else if (
      val.includes("全选") &&
      val.length - 1 < options.length &&
      end == "全选"
    ) {
      val = [];
      options.map(item => {
        val.push(item.value);
      });
      val.unshift("全选");
      // this.value = val;
    //   console.log("444===", this.value, val);
    } else if (val.includes("全选") && val.length - 1 < options.length) {
      val = val.filter(item => {
        return item !== "全选";
      });
      // this.value = val;
    //   console.log("555===", this.value, val);
    }
    // 注意,加上  this.value = val,确保勾选值同步
    // this.value = val;
    return val;
    console.log("666===", this.value, val);
  }

引用:blog.csdn.net/maidu_xbd/a…