前端使用模糊搜索fuse.js和拼音搜索pinyin-match提升搜索体验

纯前端搜索常规实现就是字符串匹配(includes/indexOf), 使用模糊搜索和拼音搜索可以让搜索体验更好,模糊搜索推荐 fuse.js,拼音搜索推荐 pinyin-match。这两个库都不大,pinyin-match 27KB,fuse.js 不到20KB,体积负担不重,比起引入一个庞大的拼音库轻量很多。

如果再能高亮匹配字符就更完美了。模糊搜索fuse.js可以直接字符正则匹配替换,拼音搜索pinyin-match会返回位置信息,根据位置信息截取字符串即可。

以下是针对 Vue3 的实现代码:

js 复制代码
let Fuse;
let Pinyin;

const searchValue = ref('');
const list = ref([]);

const searchList = computed(() => {
  list.value.forEach(item => (item.titleSearch = void 0));
  if (!searchValue.value) return list.value;

  try {
    // 模糊搜索
    const fuse = new Fuse(list.value, {
      keys: ['title'],
      threshold: 0.5,
    });
    const fuseList = fuse.search(searchValue.value).map(m => {
      m.item.titleSearch = m.item.title.replace(new RegExp(`[${searchValue.value}]`, 'gi'), s => `<span class="search-target">${s}</span>`);
      return m.item;
    });
    // 拼音搜索
    const pinyinList = list.value.filter(m => {
      if (fuseList.find(f => f.objId === m.objId)) return false;
      const match = Pinyin.match(m.title, searchValue.value);
      if (match) {
        console.log(m.title, match);
        m.titleSearch = `${m.title.slice(0, match[0])}<span class="search-target">${m.title.slice(match[0], match[1] + 1)}</span>${m.title.slice(
          match[1] + 1
        )}`;
      }
      return match;
    });

    return fuseList.concat(pinyinList);
  } catch (error) {
    console.log(error);
    return list.value.filter(f => f.title.toLowerCase().includes(searchValue.value.toLowerCase()));
  }
});

onMounted(() => {
  importSearchLib();
})

function importSearchLib() {
  // 模糊搜索库,异步加载
  import('fuse.js')
    .then(module => {
      Fuse = module.default;
    })
    .catch(err => {
      console.log(err);
    });
  // 拼音搜索库,异步加载
  import('pinyin-match')
    .then(module => {
      Pinyin = module.default;
    })
    .catch(err => {
      console.log(err);
    });
}
  • list.value.forEach(item => (item.titleSearch = void 0)); 用于提前声明增加响应式属性 titleSearch,该字段是含高亮匹配字符的富文本。

  • return list.value.filter(f => f.title.toLowerCase().includes(searchValue.value.toLowerCase())); 错误回退机制,如果 fuse.js 或 pinyin-match 使用中报错了,回退到常规的字符串匹配(includes/indexOf)搜索。

  • importSearchLib() 异步加载 fuse.jspinyin-match,虽然这两个库都不大,但搜索一般是用户主动触发,没必要在页面加载过程中引入,难免拖慢页面加载,上面的实现就是放到了 onMounted 钩子中等 DOM 装载完毕才去异步加载这两个库。

  • import('fuse.js') 如果出现如下语法格式化错误提醒:

Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node16', 'node18', or 'nodenext'.ts-plugin(1323)

改一下 tsconfig.json 的配置即可:

json 复制代码
{
  "compilerOptions": {
    "module": "ES2020",
    "target": "ES2020",
  }
}
相关推荐
子兮曰2 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰2 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万2 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝2 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋2 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁2 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
汉堡大王95272 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大2 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师2 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端
沙蒿同学2 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端