当前位置:首页 > VUE

vue实现拼音模糊搜索

2026-02-23 17:09:07VUE

实现思路

拼音模糊搜索的核心是将中文转换为拼音,并在搜索时匹配拼音或拼音首字母。需要借助第三方库将中文转换为拼音,并处理用户输入的搜索词。

vue实现拼音模糊搜索

安装拼音转换库

推荐使用 pinyin-propinyin 库。以 pinyin-pro 为例:

vue实现拼音模糊搜索

npm install pinyin-pro

核心代码实现

<template>
  <div>
    <input v-model="searchText" placeholder="输入搜索词" />
    <ul>
      <li v-for="item in filteredList" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
import { pinyin } from 'pinyin-pro';

export default {
  data() {
    return {
      searchText: '',
      originalList: [
        { id: 1, name: '苹果' },
        { id: 2, name: '香蕉' },
        { id: 3, name: '橙子' }
      ]
    };
  },
  computed: {
    filteredList() {
      if (!this.searchText.trim()) return this.originalList;

      const searchKey = this.searchText.toLowerCase();
      return this.originalList.filter(item => {
        // 获取完整拼音
        const fullPinyin = pinyin(item.name, { toneType: 'none' }).replace(/\s+/g, '');
        // 获取首字母
        const initials = pinyin(item.name, { pattern: 'first', toneType: 'none' }).replace(/\s+/g, '');

        return (
          item.name.includes(searchKey) || // 中文匹配
          fullPinyin.includes(searchKey) || // 全拼音匹配
          initials.includes(searchKey) // 首字母匹配
        );
      });
    }
  }
};
</script>

优化方案

对于大数据量的场景,可以预先计算拼音并缓存:

created() {
  this.enhancedList = this.originalList.map(item => ({
    ...item,
    fullPinyin: pinyin(item.name, { toneType: 'none' }).replace(/\s+/g, ''),
    initials: pinyin(item.name, { pattern: 'first', toneType: 'none' }).replace(/\s+/g, '')
  }));
},
computed: {
  filteredList() {
    return this.enhancedList.filter(item => 
      item.name.includes(this.searchText) ||
      item.fullPinyin.includes(this.searchText.toLowerCase()) ||
      item.initials.includes(this.searchText.toLowerCase())
    );
  }
}

高级功能扩展

实现拼音分词搜索(如"ping guo"匹配"苹果"):

// 在过滤逻辑中添加分词匹配
const searchKeys = this.searchText.toLowerCase().split(/\s+/);
return fullPinyin.includes(searchKeys.join('')) || 
       searchKeys.every(key => fullPinyin.includes(key));

注意事项

  1. 拼音库需要选择支持多音字处理的版本
  2. 搜索时建议统一转为小写比较
  3. 性能敏感场景建议使用Web Worker进行拼音计算
  4. 移动端可能需要考虑输入法联想词的兼容处理

标签: 拼音模糊
分享给朋友:

相关文章

vue实现汉子转拼音

vue实现汉子转拼音

使用 pinyin 库实现汉字转拼音 在 Vue 项目中安装 pinyin 库 npm install pinyin 在组件中引入并使用 import pinyin from 'pinyin'…

tree模糊搜索实现vue

tree模糊搜索实现vue

实现 Vue 中的 Tree 模糊搜索 在 Vue 中实现 Tree 组件的模糊搜索功能,通常需要结合递归组件、过滤算法和动态渲染。以下是具体实现方法: 递归组件结构 定义一个递归的 Tree 组件…

php实现模糊搜索

php实现模糊搜索

模糊搜索的实现方法 在PHP中实现模糊搜索可以通过多种方式,包括使用SQL的LIKE操作符、正则表达式、全文索引或第三方搜索引擎。以下是几种常见的方法: 使用SQL的LIKE操作符 LIKE操作符是…

js实现模糊搜索

js实现模糊搜索

实现模糊搜索的基本思路 模糊搜索的核心是通过输入的关键词匹配目标数据,允许存在一定的不完全匹配。常见的实现方式包括字符串包含检查、正则表达式匹配或使用第三方库。 使用字符串的 includes 方法…

js实现汉字 拼音

js实现汉字 拼音

汉字转拼音的实现方法 在JavaScript中实现汉字转拼音可以通过以下几种方式: 使用第三方库 最简便的方法是使用现成的拼音转换库,如pinyin或pinyin-pro: // 使用pi…

js实现模糊效果

js实现模糊效果

实现模糊效果的方法 在JavaScript中实现模糊效果可以通过多种方式,以下是几种常见的方法: 使用CSS滤镜 通过CSS的filter属性可以轻松实现模糊效果。JavaScript可以动态修改元…