如何在Nuxt Content中实现类似Hugo的标签关联相关文章功能?
实现Nuxt Content基于标签匹配的相关文章功能
完全可行,你可以通过以下步骤实现基于标签重合数量排序的相关文章列表:
1. 获取文章数据
在你的文章详情页面(比如 pages/[...slug].vue)中,先获取所有文章数据以及当前文章的信息:
<script setup> const { data: allArticles } = await useContent('articles') const route = useRoute() // 获取当前文章 const currentArticle = allArticles.value.find(article => article._path === `/${route.params.slug.join('/')}`) </script>
2. 计算标签匹配度并筛选相关文章
编写一个函数来计算每篇文章与当前文章的标签重合数量,然后按匹配数降序排序,取前3篇:
<script setup> // ... 之前的代码 // 计算相关文章 const getRelatedArticles = () => { if (!currentArticle?.tags) return [] return allArticles.value .filter(article => article._path !== currentArticle._path && article.tags) // 排除当前文章且有标签的文章 .map(article => { // 计算标签重合数量 const matchCount = article.tags.filter(tag => currentArticle.tags.includes(tag)).length return { ...article, matchCount } }) .sort((a, b) => b.matchCount - a.matchCount) // 按匹配数降序 .slice(0, 3) // 取前3篇 } const relatedArticles = getRelatedArticles() </script>
3. 渲染相关文章列表
在模板中直接渲染筛选后的相关文章:
<template> <!-- 当前文章内容 --> <div class="article-content"> <h1>{{ currentArticle.title }}</h1> <ContentRenderer :value="currentArticle" /> </div> <!-- 相关文章 --> <div class="related-articles" v-if="relatedArticles.length"> <h2>相关文章</h2> <ul> <li v-for="article in relatedArticles" :key="article._path"> <NuxtLink :to="article._path">{{ article.title }}</NuxtLink> <p>匹配标签数: {{ article.matchCount }}</p> </li> </ul> </div> </template>
注意事项
- 确保你的文章frontmatter中包含
tags字段(比如tags: ["前端", "Nuxt"]) - 如果需要忽略标签大小写,可以在匹配时统一转为小写(比如
tag.toLowerCase()) - 若所有文章标签匹配数都为0,会返回空列表,你可以添加兜底内容
内容的提问来源于stack exchange,提问作者Jala015
相关产品推荐
相关产品推荐

