在<option>中添加一项 ‘全选’ ,并且带搜索功能,回退搜索条件,依然生效。
父组件使用:
<all-select
v-if="funcsList.length"
:select_options="funcsList"
@update="funcsChange">
</all-select>
var vm = new Vue({
el: '#app',
data: {
funcsList:[],
},
methods: {
funcsChange(val) {
let selectArray = val.filter(item=>item!='全选')
},
}
注册自定义组件:
Vue.component('all-select', {
data() {
return {
selectedArr: [],
filteredOptions: [],
}
},
props: {
select_options:{
type:Array,
default(){
return []
}
},
},
watch:{
select_options:function () {
this.selectedArr = []
}
},
created(){
this.filteredOptions = [...this.select_options]
},
methods: {
selectAll() {
if (this.selectedArr.length < this.filteredOptions.length) {
this.filteredOptions.map((item) => {
this.selectedArr.push(item.value)
})
} else { // 取消全选
this.selectedArr = [];
}
},
changeSelect(val) {
if (!val.includes('全选') && val.length === this.select_options.length) {
this.selectedArr.unshift('全选')
}
},
removeTag(val) {
if (val === '全选') {
this.selectedArr = [];
}
this.$emit('update',this.selectedArr);
},
handleFilter(query) {
if (query) {
this.filteredOptions = this.select_options.filter(item => {
return item.label.includes(query);
});
} else {
this.filteredOptions = [...this.select_options];
}
},
visibleChange(flag) {
if (flag) {
this.filteredOptions = [...this.select_options]
}else {
this.$emit('update',this.selectedArr);
}
}
},
template: `<el-select
size="mini"
multiple
filterable
reserve-keyword
clearable
:disabled="disabled"
v-model='selectedArr'
:loading="mulSelectLoading"
:collapse-tags="collapseTags"
placeholder='请选择'
@change='changeSelect'
@visible-change="visibleChange"
:filter-method="handleFilter"
@remove-tag='removeTag'>
<el-option label='全选' value='全选' @click.native.stop="selectAll" v- if="select_options.length">
</el-option>
<el-option v-for='item in filteredOptions' :key='item.value' :label='item.label' :value='item.value'></el-option>
</el-select>`
});