需求:用户要求打出首字母就能搜索到内容,而不是打汉字。
需求分析:element自带搜索功能,支持汉字搜索,拼音的话需要引入第三方插件了。经过实验 pinyin-match完美实现。
解决过程:
-
首先安装
npm install pinyin-match --save
-
全局引用和局部引用皆可,这里我们使用了局部引用
import pinyin from "pinyin-match";
-
给select标签添加
filterable :filter-method="pinyingMatch"
-
添加自定义搜索方法
pinyingMatch(val) {
var that = this
const pinyingMatch = require("pinyin-match");
if (val) {
var result = [];
//
//注意otherList是内容数组,根据自己项目修改
that.otherList.forEach((e) => {
//注意,e.employeeName是遍历数组之后的键,按需修改
var m = pinyingMatch.match(e.employeeName, val);
// console.log(m);
if (m) {
result.push(e);
}
});
//搜索到相应的数据就把符合条件的n个数据赋值brand
that.otherList = result;
} else {
//没有搜索到数据,就还展示所有的brand
//copyotherList也是内容数组,为了显示全部,需要添加进之前的内容
that.otherList = that.copyotherList;
}
}
成功解决。
发现了一些BUG:elementUI的下拉选择,每次点击×删除之后,v-model绑定的数据没有删除,所以要添加@clear方法,将data清空,同时把otherList还原。
又出现了Bug,每次输入拼音字母,输入框的字母都会消失,这是由于v-for遍历数组时加入了Index,每次Index变化就会导致这个情况,去掉即可。