<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
}
}
}