需要注意的地方
1. 为了在匹配不到数据时也保留其输入的值,可以用 filter-method 自定义筛选
2. el-select添加上filterable之后,点击展开,点击收起,会导致focus和blur事件不触发,但点击页面其他地方才可正常触发 ,可利用visible-change 事件来解决些问题
3. input获取焦点时保留其value值用focus事件做相关赋值处理
具体实现代码如下
1 <template> 2 <el-select id="selectInput" v-model="value" filterable placeholder="请选择" ref="searchSelect" :filter-method="dataFilter" @visible-change="visibleChange" @focus="selectFocus" @blur="selectBlur" @change="selectChange"> 3 <el-option 4 v-for="item in options" 5 :key="item.value" 6 :label="item.label" 7 :value="item.value"> 8 </el-option> 9 </el-select> 10 </template> 11 12 <script> 13 export default { 14 data() { 15 return { 16 options: [{ 17 value: '选项1', 18 label: '黄金糕' 19 }, { 20 value: '选项2', 21 label: '双皮奶' 22 }], 23 optionsFilter: [{ 24 value: '选项1', 25 label: '黄金糕' 26 }, { 27 value: '选项2', 28 label: '双皮奶' 29 }], 30 value: '' 31 } 32 }, 33 methods: { 34 dataFilter(val) { 35 this.value = val; 36 if (val) { 37 this.options = this.optionsFilter.filter((item) => { 38 if (item.label.includes(val) || item.label.toUpperCase().includes(val.toUpperCase())) { 39 return true 40 } 41 }) 42 } else { 43 this.options = this.optionsFilter; 44 } 45 }, 46 selectFocus(e){ 47 let value = e.target.value; 48 setTimeout(() => { 49 let input = this.$refs.searchSelect.$children[0].$refs.input; 50 input.value = value; 51 }) 52 }, 53 selectBlur(){ 54 //console.log('失去') 55 }, 56 selectChange(){ 57 58 }, 59 visibleChange(val){ 60 if(!val){ 61 let input = this.$refs.searchSelect.$children[0].$refs.input; 62 input.blur(); 63 } 64 65 } 66 } 67 } 68 </script>