前言
在日常使用el-select过程中,数据量一多就会要使用检索的方式更快找到数据,默认通过label匹配关键字,但有时还需要能够支持更多的字段,例如拼音、五笔、编码等, 官方提供了filter-method自定义检索。下面说明优缺点及改进方式
filter-method
filter-method方式主要问题是要维护原始的列表数据,同时在下拉框关闭的时候还原列表项,当在同一个组件里面有多个需要这样处理时,容易造成业务无关代码的耦合度。
Vue.extend 增强ElOption
通过查看源码了解到label检索方式:
queryChange(query) {
this.visible = new RegExp(escapeRegexpString(query), 'i').test(this.currentLabel) || this.created;
if (!this.visible) {
this.select.filteredOptionsCount--;
}
}
这里的this.currentLabel就是prop的label,由此想到,能否通过Vue.extend继承方式修改:
props: {
labelFilter: String
...
}
queryChange(query) {
this.visible = new RegExp(escapeRegexpString(query), 'i').test(this.labelFilter || this.currentLabel) || this.created;
if (!this.visible) {
this.select.filteredOptionsCount--;
}
}
<el-select>
<el-option-filter :labelFilter="`${item.label} ${item.pinyin} ${item.wubi} ${item.code}`"></el-option-filter>
</el-select>
结尾
如果觉得有用,请回复 有用,另求内推(合肥)