如果您有一小部分帖子,我认为您可以创建一个搜索组件来获取所有帖子,然后使用js-search 或flexsearch 之类的东西来索引它们。
在非页面组件中(不在src/pages文件夹中),您可以使用StaticQuery获取所有帖子的信息。
假设你有这个 graphql 查询结果:
data: {
allMarkdownRemark: {
edges: [{
node: {
id: '1234-1233...',
fields: {
slug: '/hello/'
},
frontmatter: {
title: 'hello',
tags: [ 'go', 'js' ]
}
}
}, {
node: {
id: ...
}
}]
}
}
然后您可以使用 js-search 来索引和搜索帖子:
const posts = data.allMarkdownRemark.edges.map(({ node }) => node) // unwrap edges
const postIndex = new JsSearch.Search('id')
postIndex.addIndex(['frontmatter', 'tags']) // index node.frontmatter.tags
postIndex.addIndex(['frontmatter', 'title'])
postIndex.addDocuments(posts) // add data to array
const results = postIndex.search('go')
console.log(results) // [{ id: '1234-1233...', frontmatter: { title: 'hello', tags: [ 'go', 'js' ]}}]
然后您可以将此结果存储在组件的状态中,并将结果呈现为帖子。
盖茨比的文档也有一个 guide 用于向您的网站添加搜索,但我认为 js-search 部分有点压倒性。