
要实现全局搜索标签(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'
export default {
plugins: [
slimsearchPlugin({
// 确保启用了内容索引(如果需要同时搜索正文)
indexContent: true,
// 自定义字段:添加标签搜索
customFields: [
{
name: 'tags',
getter: (page) => page.frontmatter.tags,
formatter: '标签: $content',
},
],
}),
],
}
处理不同格式的Tag
标签可能有不同的格式,你可以通过 getter 函数灵活处理:
customFields: [
{
name: 'tags',
getter: (page) => {
const tags = page.frontmatter.tags
// 处理字符串格式: "Vue,React"
if (typeof tags === 'string') {
return tags.split(',').map(tag => tag.trim())
}
// 处理数组格式: ["Vue", "React"]
if (Array.isArray(tags)) {
return tags
}
// 处理单个标签: "Vue"
if (typeof tags === 'string') {
return [tags]
}
return null
},
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")

658



被折叠的 条评论
为什么被折叠?



