安装pinyin-match插件
yarn add pinyin-match
应用
<el-selectv-model="name"filterable:filter-method="handlePinYinSearch"><el-optionv-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变化就会导致输入框的字母消失,需要去掉。