拼音搜索的简单实现方案

修改时间: 2020-05-28 13:40:00 PM

文章时间:2020年5月28日 13:37:18
解决问题:在搜索框搜索某些东西的时候,我们经常输入了拼音,依然也可以显示搜索出的文字。
所用插件:ChinesePY.js
投稿人:梦群同学

ChinesePY 嵌入使用方法

首先在Github下载ChinesePY.js [下载地址]

下载完成后在项目 main.js 中引入

import Pinyin from './ChinesePY' // 你的该文件位置

使用方法及返回格式

Pinyin.GetJP('中国') // 获取简拼 -> ZH (注意 简拼返回值为大写)
Pinyin.GetQP('中国') // 获取全拼 -> zhongguo
Pinyin.GetHP('中国') // 获取混拼 -> zhongg

手写自己的根据拼音查询 公共函数

Vue.prototype.$pinyin = (restaurant: string, queryString: string): boolean => {
  const jp = Pinyin.GetJP(restaurant)
  const qp = Pinyin.GetQP(restaurant)
  const hp = Pinyin.GetHP(restaurant)
  const rgx = new RegExp(queryString, 'gi')
  return rgx.test(jp) || rgx.test(qp) || rgx.test(hp)
}

// restaurant -> 需要检索的字符串
// queryString -> 输入的字符串

使用

{
    methods: {
        handle() {
            const value = this.$pinyin('中国', searchString)
            if(value) {
                // todu something
            } else {
                // todu something
            }
        }
    }
}

添加新评论