本地搜索(@vuepress/plugin-slimsearch替换vuepress-plugin-search-pro)

要实现全局搜索标签(Tag),你需要使用slimsearch插件的customFields配置项。这个功能允许你将页面中的自定义数据(比如标签、分类、作者等)添加到搜索索引中。

{"@vuepress/plugin-slimsearch":"2.0.0-rc.121"}

🏷️ 全局搜索Tag的配置方案

基础配置:搜索文章标签

假设你在文章的 Frontmatter 中是这样定义标签的:

--- title: 我的文章 tags: - Vue.js - 前端开发 - JavaScript ---

.vuepress/config.ts中添加如下配置:

import{slimsearchPlugin}from'@vuepress/plugin-slimsearch'exportdefault{plugins:[slimsearchPlugin({// 确保启用了内容索引(如果需要同时搜索正文)indexContent:true,// 自定义字段:添加标签搜索customFields:[{name:'tags',getter:(page)=>page.frontmatter.tags,formatter:'标签: $content',},],}),],}

处理不同格式的Tag

标签可能有不同的格式,你可以通过getter函数灵活处理:

customFields:[{name:'tags',getter:(page)=>{consttags=page.frontmatter.tags// 处理字符串格式: "Vue,React"if(typeoftags==='string'){returntags.split(',').map(tag=>tag.trim())}// 处理数组格式: ["Vue", "React"]if(Array.isArray(tags)){returntags}// 处理单个标签: "Vue"if(typeoftags==='string'){return[tags]}returnnull},formatter:'标签: $content',},]

多语言支持

如果你的站点有多语言,可以为不同语言设置不同的显示格式:

customFields:[{name:'tags',getter:(page)=>page.frontmatter.tags,formatter:{'/':'Tags: $content','/zh/':'标签: $content','/jp/':'タグ: $content',},},]

同时搜索多个字段

如果你想同时搜索标签、分类和作者:

customFields:[{name:'tags',getter:(page)=>page.frontmatter.tags,formatter:'🏷️ $content',},{name:'category',getter:(page)=>page.frontmatter.category,formatter:'📁 $content',},{name:'author',getter:(page)=>page.frontmatter.author,formatter:'👤 $content',},]

🔧 注意事项

1. 确保索引生效

  • 添加customFields后,需要删除.vuepress/.temp.vuepress/dist并重新构建
  • 如果搜索不到,检查 Frontmatter 中是否有search: false禁用索引

2. 调试技巧

在浏览器控制台查看索引是否包含标签数据:

// 查看搜索插件的内部状态window.__VUEPRESS__?.__plugins?.slimsearch?.index

3. 版本兼容性

  • 确保@vuepress/plugin-slimsearch的版本与你的 VuePress 核心版本兼容
  • 如果使用vuepress-theme-hope,建议通过主题的plugins.slimsearch配置,避免重复引入

4. 搜索效果

配置完成后,当你搜索"Vue.js"时,搜索结果中会出现:

  • 标题包含"Vue.js"的文章
  • 正文包含"Vue.js"的文章(如果开启indexContent
  • 标签包含"Vue.js"的文章(会显示为"标签: Vue.js")