- 安装pinyin-match插件
yarn add pinyin-match
- 应用
<el-select
v-model="name"
filterable
:filter-method="handlePinYinSearch">
<el-option
v-for="str in qxList"
:key="str.name"
:value="str.name"
:label="str.name"
></el-option>
</el-select>
import PinyinMatch from 'pinyin-match' // 引用
export default{
data(){
return {
name: ''
qxList: [], // 数据源
qxListCopy: [], // copy 的数据源
}
},
methods: {
// 拼音搜索
handlePinYinSearch(val) {
if (val) {
const result = this.qxListCopy.reduce((acc, item) => {
const m = PinyinMatch.match(item.name, val)
if (m) {
acc.push(item)
}
return acc
}, [])
this.qxList = result
} else {
this.qxList = this.qxListCopy
}
},
}
}
注意:每次输入拼音字母,如果v-for遍历数组时key为index,每次index变化就会导致输入框的字母消失,需要去掉。