Nuxt 生态 精选推荐

Nuxt 3 内容模块完全指南

HTMLPAGE 团队
12 分钟阅读

深入理解 Nuxt Content 模块,构建基于文件的内容管理系统,实现博客和文档网站

#Nuxt 3 #Nuxt Content #静态生成 #Markdown

Nuxt 3 内容模块完全指南

什么是 Nuxt Content?

Nuxt Content 是 Nuxt 3 的官方内容管理模块,专门为博客、文档和知识库等内容驱动的网站设计。它将文件系统视为数据库,让你用纯文本文件快速构建动态内容网站。

核心优势

Nuxt Content 让你可以:

  • 用 Markdown 编写内容:无需数据库,所有内容都是代码
  • 自动生成路由:文件结构自动对应 URL 路由
  • 支持多种格式:Markdown、YAML、CSV、JSON 等一应俱全
  • 完整的代码高亮:内置 Shiki 引擎,支持 180+ 种语言
  • MDC 语法:在 Markdown 中使用 Vue 组件
  • 全文搜索:内置搜索功能,无需额外配置
  • 热重载开发:修改内容即时看到效果

这种方法非常适合需要快速迭代和版本控制的项目。

安装配置

基础安装

# 创建新项目
npx nuxi@latest init my-content-site -t content

# 或在现有 Nuxt 项目中安装
npm install @nuxt/content

配置文件

nuxt.config.ts 中配置:

export default defineNuxtConfig({
  modules: ['@nuxt/content'],
  content: {
    // 代码高亮配置
    highlight: {
      theme: 'github-dark',
      preload: ['ts', 'js', 'css', 'java', 'python', 'sql']
    },
    // 文件存储位置
    sources: {
      content: './content'
    },
    // 缓存和性能
    cacheAssets: true,
    // Markdown 渲染选项
    markdown: {
      anchorLinks: false,
      toc: {
        depth: 3,
        searchDepth: 3
      }
    }
  }
})

基本用法

1. 创建内容结构

按照以下结构组织内容:

content/
├── articles/
│   ├── my-first-post.md
│   ├── advanced-topic.md
│   └── tips-and-tricks.md
├── docs/
│   ├── getting-started.md
│   └── api-reference.md
└── pages.yml

2. 编写 Markdown 文件

Frontmatter 定义元数据,正文是内容:

---
title: 如何使用 Nuxt Content
description: 完整的使用指南和最佳实践
author: HTMLPAGE 团队
date: 2025-12-04
tags:
  - Nuxt
  - Content
  - SSG
cover: /images/nuxt-content.jpg
---

# 开始使用

这是文章的正文内容...

## 小节标题

更多内容...

3. 查询和渲染内容

获取所有文章:

<script setup>
const { data: articles } = await useAsyncData('articles', () =>
  queryContent('articles').sort({ date: -1 }).find()
)
</script>

<template>
  <div>
    <article v-for="article in articles" :key="article._id">
      <h2>{{ article.title }}</h2>
      <p>{{ article.description }}</p>
    </article>
  </div>
</template>

获取单篇文章:

<script setup>
const route = useRoute()
const { data: article } = await useAsyncData('article', () =>
  queryContent('articles').where({ _path: `/articles/${route.params.slug}` }).findOne()
)
</script>

<template>
  <article v-if="article">
    <h1>{{ article.title }}</h1>
    <ContentDoc :value="article" />
  </article>
</template>

高级特性

MDC 语法 - 在 Markdown 中使用 Vue 组件

MDC(Markdown Components)让你在 Markdown 中使用 Vue 组件:

# 我的文章

这是普通段落。

::alert{type="info"}
这是一个信息提示框,使用 Vue 组件渲染
::

::card
#title
卡片标题

#default
这是卡片内容,支持 **Markdown** 格式
::

::tabs
#tab1
第一个标签

#tab2
第二个标签
::

代码块增强

代码块支持丰富的功能:

```typescript [src/composables/useAuth.ts]
// 代码块标题
export const useAuth = () => {
  const user = ref(null)
  
  return { user }
}
```

```javascript [highlight='2-4']
// 高亮特定行
const items = [1, 2, 3, 4, 5]
const doubled = items.map(n => n * 2)
const filtered = doubled.filter(n => n > 5)
console.log(filtered) // [6, 8, 10]
```

文件元信息(Front Matter 查询)

<script setup>
// 查询特定标签的文章
const articles = await queryContent('articles')
  .where({ tags: { $contains: 'Nuxt' } })
  .find()

// 查询特定日期范围的文章
const recentArticles = await queryContent('articles')
  .where({
    date: { $gte: new Date('2025-01-01') }
  })
  .sort({ date: -1 })
  .limit(5)
  .find()
</script>

最佳实践

1. 目录和文件组织

content/
├── blogs/              # 博客文章
│   └── [year]/
│       └── [slug].md
├── docs/               # 文档
│   ├── getting-started.md
│   ├── api/
│   │   └── reference.md
│   └── guide/
│       └── installation.md
└── changelog/          # 更新日志
    └── [version].md

2. 完整的 Frontmatter 示例

---
# 基本信息
title: 文章标题
description: 简明扼要的描述
category: 分类名

# SEO 优化
keywords: [关键词1, 关键词2]
ogImage: /images/og-image.jpg

# 元数据
author: 作者名
date: 2025-12-04
updated: 2025-12-05
readingTime: 5

# 内容标记
draft: false
featured: true
tags: [标签1, 标签2]

# 链接
related: [/docs/another-post, /blogs/2025/similar-topic]
---

3. 创建自定义 MDC 组件

<!-- components/content/Alert.vue -->
<template>
  <div :class="`alert alert-${type}`">
    <slot />
  </div>
</template>

<script setup>
defineProps({
  type: {
    type: String,
    default: 'info',
    validator: (v) => ['info', 'warning', 'error'].includes(v)
  }
})
</script>

<style scoped>
.alert {
  padding: 1rem;
  border-radius: 0.5rem;
  border-left: 4px solid;
}

.alert-info {
  background: #dbeafe;
  border-color: #0ea5e9;
  color: #0c4a6e;
}
</style>

4. SEO 优化

<script setup>
const route = useRoute()
const { data: post } = await useAsyncData(() =>
  queryContent(route.path).findOne()
)

// 设置 SEO 元数据
useHead({
  title: post.value.title,
  meta: [
    { name: 'description', content: post.value.description },
    { name: 'keywords', content: post.value.keywords?.join(', ') },
    { property: 'og:title', content: post.value.title },
    { property: 'og:description', content: post.value.description },
    { property: 'og:image', content: post.value.ogImage },
    { name: 'twitter:card', content: 'summary_large_image' }
  ]
})
</script>

5. 构建性能

  • 预构建高频访问的内容
  • 使用增量静态再生(ISR)更新内容
  • 为列表页面添加分页,减少初始加载

总结

Nuxt Content 将内容管理简化到极致,让你专注于设计和功能。特别适合需要快速上线和持续更新的项目。配合 Nuxt 3 的强大功能,你可以快速构建既精美又高性能的内容网站。

开始使用 Nuxt Content 的最好方式就是立即创建你的第一个项目!