如何在vue+element中实现选择框和穿梭框的根据拼音以及拼音首字母以及汉字的模糊搜索

1.汉字: 直接添加对应的 filterable
 
 
2.拼音: 穿梭框和选择器的实现方式有所不同
 
选择器:
 
<1>下载pinyin-match:   npm i --save pinyin-match
 
<2>在main.js引入并注册为全局属性
 
       import PinyinMatch from 'pinyin-match';
      Vue.prototype.$pinyinmatch = PinyinMatch;
 
<3>为需要的选择器添加自定义过滤方法
 
   :filter-method="PinyinMatchsq"
 
实现方法:
 
PinyinMatchsq(val) {
let PinyinMatch = this.$pinyinmatch;
if (val) {
let result = [];
this.salepreInfo.forEach(i => {
let m = PinyinMatch.match(i.username, val);
if (m) {
result.push(i);
}
});
this.salepreInfo = result;
} else {
this.salepreInfo = this.copysalepreInfo;
}
}
 
 
穿梭框:
 
因为穿梭框的匹配机制和选择器有所不同,因此采用其他方案解决。
<1>自己定义一个拼音库的js文件 pinyin.js:
 
链接:  https://www.cnblogs.com/lzcblog/p/10642364.html  
 
<2>实现将汉字转化为拼音以及拼音首字母组合的方法并放到一个js文件中 vue-py.js。
 
 
import pinyin from "./pinyin.js";
export default {
//转化为全拼音
chineseToPinYin: function(l1) {
var l2 = l1.length;
var I1 = "";
var reg = new RegExp("[a-zA-Z0-9]");
for (var i = 0; i < l2; i++) {
var val = l1.substr(i, 1);
var name = this.arraySearch(val, pinyin);
if (reg.test(val)) {
I1 += val;
} else if (name !== false) {
I1 += name;
}
}
I1 = I1.replace(/ /g, "-");
while (I1.indexOf("--") > 0) {
I1 = I1.replace("--", "-");
}
return I1;
},
//转化为首字母组合
CC2PYF: function(l1) {
var l2 = l1.length;
var I1 = "";
var reg = new RegExp("[a-zA-Z0-9- ]");
for (var i = 0; i < l2; i++) {
var val = l1.substr(i, 1);
var name = this.arraySearch(val, pinyin);
if (reg.test(val)) {
I1 += val;
} else if (name !== false) {
I1 += name.substring(0, 1);
}
}
I1 = I1.replace(/ /g, "-");
while (I1.indexOf("--") > 0) {
I1 = I1.replace("--", "-");
}
return I1;
},
arraySearch: function(l1, l2) {
for (var name in pinyin) {
if (pinyin[name].indexOf(l1) !== -1) {
return this.ucfirst(name);
}
}
return false;
},
ucfirst: function(l1) {
if (l1.length > 0) {
var first = l1.substr(0, 1).toUpperCase();
var spare = l1.substr(1, l1.length);
return first + spare;
}
}
};
 
 
<3>在穿梭框中绑定自定义的过滤方法
 
 
:filter-method="PinyinMatch"
 
 
在data中实现过滤方法
 
PinyinMatch(query, val) {
let result =
val.pinyin.indexOf(query) > -1 ||
val.deptUserName.indexOf(query) > -1 ||
val.jx.indexOf(query) > -1;
return result;
}
原文地址:https://www.cnblogs.com/lzcblog/p/10579899.html