级联选择器拼音搜索
1、安装插件pinyin-pro
cnpm install pinyin-pro
2、核心代码如下
<el-cascader
ref="productManagerRef"
:props="productManagerProps"
filterable
:filter-method="filterMethod"
v-model="productManagerAssign"
:options="productManagerList"
:show-all-levels="false"
@change="productInfo"
></el-cascader>
import { pinyin } from 'pinyin-pro';
function filterMethod(node: any, keyword: string) {
if (node.data.roleName.includes(keyword)) {
return true;
}
if (!node.data.pinyin) {
try {
node.data.pinyin = pinyin(node.data.roleName, { toneType: 'none' }).replace(/ /g, '');
} catch (error) {
node.data.pinyin = '';
}
}
return node.data.pinyin.includes(keyword);
}
3、注意:在change方法中清空搜索值,需要在获取的展示数据中添加pin对应字段
function getProductManager() {
let params = {
nickName: null,
};
findAllRoleInfosApi(params).then((res: any) => {
let { secondRoleTypes, firstRoleTypes } = res.data;
let allRoles = res.data.allRoles;
for (let i = 0; i < firstRoleTypes.length; i++) {
firstRoleTypes[i].children = [];
for (let j = 0; j < secondRoleTypes.length; j++) {
if (firstRoleTypes[i].roleId === secondRoleTypes[j].parentRoleId) {
firstRoleTypes[i].children.push(secondRoleTypes[j]);
}
secondRoleTypes[j].children = [];
for (let k = 0; k < allRoles.length; k++) {
if ( secondRoleTypes[j].roleId === allRoles[k].parentRoleId ) {
// 重点在这!!!!
allRoles[k].pinyin = pinyin(allRoles[k].roleName, { toneType: 'none' }).replace(/ /g, '');
secondRoleTypes[j].children.push(allRoles[k]);
}
}
}
}
state.productManagerList = firstRoleTypes;
});
change方法:中添加productManagerRef.value.searchInputValue = '';
function productInfo() {
// 清空搜索值
productManagerRef.value.searchInputValue = '';
// 用来关闭cascader下拉框
productManagerRef.value.handleInput();
}