Vue项目中 实现ElementUi框架el-select拼音搜索功能
拼音搜索功能
前言:由于项目需要,且elementUI中的el-select只支持中文或英文匹配,不支持全拼音匹配或拼音首字母匹配,故封装该功能。
-
代码依赖 ? 第三方包:pinyin-match ? 地址: https://github.com/xmflswood/pinyin-match -
代码支持:
- 全拼音匹配 当输入beijing 可以匹配如下:“北京” “背景” “北京烤鸭”
- 拼音首字母匹配 当输入bj时 可以匹配如下:“北京烤鸭” “布局” “编辑” “有背景”,即并不是从第一个汉字进行匹配,但需要首字母的汉字前后顺序符合。
- 全拼音但最后一个汉字拼音非完整 当输入beijin 可以匹配如下:“被禁” “北京”
- 当输入拼音退格时,动态更新options的label(这个功能实现起来比较麻烦,大概多用了80%的代码)
-
代码实现
-
el-select添加属性 <el-select
filterable
:filter-method="(val)=>{$handleMatch(val,'deptList','name')}"
@click.native="$resetOpts('deptList')">
<el-option
v-for="item in deptList"
:key="item.dictId"
:label="item.name"
:value="item.dictId"></el-option>
</el-select>
-
创建拼音搜索相关方法 import store from '@/store'
import PinyinMatch from 'pinyin-match/es/traditional.js';
export function handleMatch(val, arrName, attr){
let res = this.$pyMatch(val, this[arrName], attr)
if(res.length !== 0){
this[arrName] = res
}
}
export function pyMatch(val,options,attr){
let res = []
store.commit('copyOpts',options)
store.commit('pushValArr',val)
let sVal = store.state.tempSelect.valArr.slice(-2)[0]
if(val.length < sVal.length || val.length ===1) {
options = store.state.tempSelect.tempOptsArr[0];
}
options.forEach(item => {
let m = PinyinMatch.match(item[attr], val)
if(m){
res.push(item)
}
})
if(res.length === 0) return options
return res
}
export function resetOpts(arrName){
if(Array.isArray(this[arrName])){
if(this[arrName].length <= 1){
this[arrName] = this.$store.getters.getOriginalSelect
}
}
}
-
方法挂载到Vue实例
import { handleMatch, pyMatch, resetOpts } from './utils/pinyinMatch'
Vue.prototype.$handleMatch = handleMatch
Vue.prototype.$pyMatch = pyMatch
Vue.prototype.$resetOpts = resetOpts
-
store中创建存储options备份的对象及操作方法
state:{
tempSelect:{
tempOptsArr:[],
valArr:[]
}
},
mutations:{
copyOpts(state,payload){
if(Array.isArray(payload)){
state.tempSelect.tempOptsArr.push(payload)
}
},
pushValArr(state,val){
if(typeof val === 'string'){
state.tempSelect.valArr.push(val)
}
},
resetTemp(state){
state.tempSelect.tempOptsArr = []
state.tempSelect.valArr = []
}
},
getters:{
getOriginalSelect(state){
return state.tempSelect.tempOptsArr[0]
}
}
-
在router全局导航守卫中调用清空options备份的方法 import store from '@/store'
router.beforeEach((to, from, next) => {
if(store.state.tempSelect.tempOptsArr.length !== 0 || store.state.tempSelect.valArr.length !== 0){
store.commit('resetTemp')
}
next()
})
|