需求:需要支持首字母大写搜索
一、js库安装
npm install js-pinyin --save
二、引入
单文件:
import pinyin from 'js-pinyin'
使用标签引入:
let pinyin = require(‘js-pinyin’);
三:属性详解
// setOptions中传入对象,对象可传两个参数
// charCase参数: 输出拼音的大小写模式,0-首字母大写;1-全小写;2-全大写
// checkPolyphone:是否检查多音字
pinyin.setOptions({checkPolyphone: false, charCase: 0});
// getCamelChars: 获取拼音首字母
// getFullChars: 获取拼音
console.log(pinyin.getFullChars(‘徐’));Xu
console.log(pinyin.getCamelChars(‘徐’));X
四、使用
//keyword是输入框的值
getNode(node, keyword) {
let reg = /^[a-zA-Z]/;//正则表达式
let type = reg.test(keyword.substring(0, 1));//筛选首字符是字母的
// 判断首字符类型
if (type) {
pinyin.setOptions({ checkPolyphone: false, charCase: 0 });
let upperCase = keyword && keyword.toUpperCase(); //统一转成大写
//返回节点名字缩写大写包含输入框的值大写的节点
return (
(node.nodeName &&
pinyin.getCamelChars(node.nodeName).includes(upperCase)) ||
(node.name && pinyin.getCamelChars(node.name).includes(upperCase))
);
} else {
return (
(node.nodeName && node.nodeName.includes(keyword)) ||
(node.name && node.name.includes(keyword))
);
}
},