为el-select添加filterable属性即可启用搜索功能。默认情况下,Select 会找出所有label属性包含输入值的选项。如果希望使用其他的搜索逻辑,可以通过传入一个filter-method来实现。filter-method为一个Function,它会在输入值发生变化时调用,参数为当前输入值。
代码如下:
<template>
<section class="p-10">
<el-select clearable v-model="value" placeholder="请选择" filterable :filter-method="dataFilter">
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
</section>
</template>
<script>
export default {
data() {
return {
optionsCopy: [{
value: '1',
label: '张三'
}, {
value: '2',
label: '李四'
}],
options: [{
value: '1',
label: '张三'
}, {
value: '2',
label: '李四'
}],
value: ''
};
},
methods: {
dataFilter(val) {
this.value = val;
if (val) { //val存在
this.options = this.optionsCopy.filter((item) => {
if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase())) {
return true
}
})
} else { //val为空时,还原数组
this.options = this.optionsCopy;
}
}
}
};
</script>
当然dataFilter方法里filter也可以这样写:
dataFilter(val) {
this.value = val
if (val) {
this.options = this.optionsCopy.filter((item) => {
return item.label.indexOf(val)>-1 || item.value.indexOf(val)>-1
})
} else {
this.options = this.options2;
}
},