Tiếp theo là Bài 10 – Xây dựng Blog cá nhân bằng @nuxt/content
. Đây là module cực mạnh trong Nuxt giúp bạn tạo website dạng blog, tài liệu, documentation… chỉ bằng file Markdown.
1. Cài đặt @nuxt/content
Chạy lệnh:
npm install @nuxt/content
Thêm module vào nuxt.config.ts
:
export default defineNuxtConfig({
modules: ['@nuxt/content']
})
2. Tạo thư mục content/
và viết bài Markdown
Tạo file: content/hello-world.md
---
title: Hello World
description: Đây là bài blog đầu tiên
date: 2025-07-07
author: Johnny
---
# Hello Nuxt Content
Đây là nội dung viết bằng Markdown.
- Dễ viết
- Dễ quản lý
3. Hiển thị danh sách bài viết
Tạo trang pages/blog/index.vue
:
<script setup>
const { data: articles } = await useAsyncData(() =>
queryContent().sort({ date: -1 }).find()
)
</script>
<template>
<div>
<h1>Blog</h1>
<ul>
<li v-for="post in articles" :key="post._path">
<NuxtLink :to="post._path">{{ post.title }}</NuxtLink>
<br />
<small>{{ post.date }}</small>
</li>
</ul>
</div>
</template>
4. Hiển thị chi tiết bài viết
Tạo file: pages/blog/[...slug].vue
<script setup>
const { params } = useRoute()
const { data: post } = await useAsyncData(() =>
queryContent('/blog').where({ _path: `/blog/${params.slug}` }).findOne()
)
</script>
<template>
<article v-if="post">
<h1>{{ post.title }}</h1>
<small>{{ post.date }} – {{ post.author }}</small>
<ContentRenderer :value="post" />
</article>
</template>
ContentRenderer
là component của Nuxt để render Markdown.
5. Giao diện Markdown đẹp hơn?
Thêm theme mặc định:
// nuxt.config.ts
content: {
documentDriven: true,
highlight: {
theme: 'github-dark'
}
}
Thêm CSS trong app.vue
hoặc assets/main.css
:
.prose {
max-width: 700px;
margin: auto;
}
6. Tìm kiếm, phân trang, lọc tag?
→ Bạn có thể kết hợp queryContent()
với .where()
, .limit()
, .skip()
để làm:
queryContent().where({ author: 'Johnny' }).limit(5)
Bạn đã học được
- Cài và cấu hình
@nuxt/content
- Viết blog bằng Markdown trong thư mục
content/
- Tự động render nội dung ra HTML
- Tạo route động để xem chi tiết bài viết
- Quản lý bài viết như một CMS tĩnh
Bài tập mở rộng
- Viết thêm 3 bài blog trong
content/
- Mỗi bài có
title
,description
,date
,author
trong frontmatter - Tạo layout
blog.vue
dùng chung cho blog
Thảo luận