效果预览
安装插件 pinyin-match
cnpm i pinyin-match --save
导入插件 pinyin-match
import PinYinMatch from "pinyin-match";
在过滤方法中使用
matchFruit(searchContent) { if (searchContent) { let result = []; this.list_org.forEach((item) => { // matchResult 的值为 true/false let matchResult = PinYinMatch.match(item.label, searchContent); if (matchResult) { result.push(item); } }); this.list_filtered = result; } else { this.list_filtered = this.list_org; } },
完整范例
<template> <div class="container"> <el-select v-model="fruit" placeholder="请选择水果" filterable :filter-method="matchFruit" clearable @clear="clearFruit" > <el-option v-for="item in list_filtered" :key="item.value" :label="item.label" :value="item.value" > </el-option> </el-select> </div> </template> <script> import PinYinMatch from "pinyin-match"; export default { data() { return { fruit: "", list_org: [ { value: 1, label: "苹果", }, { value: 2, label: "香蕉", }, { value: 3, label: "梨子", }, ], list_filtered: [], }; }, mounted() { this.list_filtered = this.list_org; }, methods: { matchFruit(searchContent) { if (searchContent) { let result = []; this.list_org.forEach((item) => { // matchResult 的值为 true/false let matchResult = PinYinMatch.match(item.label, searchContent); if (matchResult) { result.push(item); } }); this.list_filtered = result; } else { this.list_filtered = this.list_org; } }, clearFruit() { this.list_filtered = this.list_org; }, }, }; </script> <style lang="scss" scoped> .container { margin: 30px; } </style>
注意事项
- el-option 的 v-for 循环中的 key 不能用 index, 否则会出现输入拼音不显示的bug,如输入 l 不显示
- 若 el-select 添加了 clearable,则需如范例添加 @clear=“clearFruit” 以便在清除内容后,将下拉列表恢复为过滤前的列表。