vue中使用element中的el-select完成全选和反选

 <el-select v-model="searchForm.firmIdList" clearable style="width:100%" filterable multiple collapse-tags placeholder="名称" @change="selectBox" @visible-change="visiblechangeOption">
       <el-checkbox v-model="isSelectAll" style="padding-left:18px" @change="selectAll">全选</el-checkbox>
       <el-checkbox v-model="isSelectReverse" style="padding-left:18px" @change="selectReverse">反选</el-checkbox>
       <el-option v-for="(item, index) in options" :key="index" :value="item.id" :label="item.name" />
  </el-select>

注:这里使用@visible-change 而不是@change 是因为 选中改变后会发送请求,为了避免频繁的向后台发送请求 就换成visible-change了,当然也可以用change;然后我这里change也绑定了事件,用来判断全选是否被选中,可以把visiblechange里的代码挪到change里 不影响的

data(){
 return{
  searchForm: {
    firmIdList:[] // 选中后的数据
   },
  isSelectAll: false,
  isSelectReverse: false,
  options:[ // 获取后端返回的数据,在这使用假数据
    {id:1, name:'name1'},
    {id:2, name:'name2'},
    {id:3, name:'name3'},
  ] 
 }
}

methods: {
 // 全选
    selectAll(val) {
      if (val) {
        this.searchForm.firmIdList = []
        this.options.every(i => this.searchForm.firmIdList.push(i.id)) // 拿到options中每条数据的id并添加到firmIdList
        if (this.isSelectReverse) {
          this.isSelectReverse = false
        }
      } else {
        this.searchForm.firmIdList = []
      }
      this.selectBox()
    },
    
    // 反选
    selectReverse(val) {
      if (val && this.isSelectAll) {
        this.isSelectAll = false
      }
      const curSelect = [...this.searchForm.firmIdList]
      const idSet = curSelect.reduce((pre, cur) => {
        pre[cur] = true
        return pre
      }, {})
      // 遍历全部,去掉在idSet中存在的id
      const result = this.options.filter(i => !idSet[i.firmId])
      const temp = []
      result.every(z => temp.push(z.firmId))
      this.searchForm.firmIdList = temp
      this.selectBox()
    },
    
    // 操作完后发送请求之类的后续操作
    visiblechangeOption(val) {
      if (!val) {
        // dosomething....
      }
    },
    
    // 全选控制
    selectBox() {
      if (this.searchForm.firmIdList && this.searchForm.firmIdList.length == this.options.length) {
        this.isSelectAll = true
      } else {
        this.isSelectAll = false
      }
    }
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值