Nuxt Content V2 使用筆記
1. 安裝Nuxt Content
- 加入到已有的Nuxt3 Project
pnpm add @nuxt/content
- 加入到
nuxt.config.ts
的modules
// nuxt.config.ts
export default defineNuxtConfig({
modules: [
'@nuxt/content'
],
content: {
// ... options
}
})
2. 建立筆記檔案資料夾
- 在根目錄建立
content
資料夾 - 在裡面建立筆記資料夾 ex:
notes
- 可以開始在裡面存放
markdown
檔案了
3. 建立 Markdown 檔案
- 在Markdown檔案內,可以使用
Frontmatter
來建立一些筆記相關資訊 - 這些資訊也同樣可以使用
Nuxt Content
的方法顯示 - 是一種方便管理每篇筆記的方法
Nuxt_Content.md
---
title: 'Nuxt Content V2'
description: '使用Nuxt Content建立個人網站筆記'
date: '2023-11-12'
category: 'Nuxt'
tags:
- NuxtContent
---
4. 建立筆記列表頁面
- 使用
useAsyncData
和queryContent
方法 - 使用
sort
方法針對日期排序
<script setup>
const { data: notesList } = await useAsyncData('notesList', () => {
return queryContent('notes').sort({ date: -1 }).find()
})
</script>
- 會取得以下物件組成的陣列,包含該篇文章的所有資訊
{
"_path": "/notes/vue",
"_dir": "notes",
"_draft": false,
"_partial": false,
"_locale": "",
"title": "Vue 權限控制",
"description": "",
"body": {
"type": "root",
"children": [],
"toc": {
"title": "",
"searchDepth": 2,
"depth": 2,
"links": []
}
},
"_type": "markdown",
"_id": "content:1.notes:20.Vue-權限控制.md",
"_source": "content",
"_file": "1.notes/20.Vue-權限控制.md",
"_extension": "md"
}
- 就可以使用
v-for
顯示需要的資料到畫面上
<template>
<ul>
<li
v-for="note in notesList"
:key="note._path"
class="my-8 border-b border-slate-600 py-4 dark:text-gray-200"
>
<NuxtLink
:to="note._path"
class="block text-2xl font-bold duration-300 hover:-translate-x-1"
>
{{ note.title }}
</NuxtLink>
<p class="my-2 line-clamp-1 opacity-70">
{{ note.description }}
</p>
<div class="mb-4 flex items-center gap-2">
<span class="pb-1"><Icon name="material-symbols:calendar-today-rounded" /></span>
<span class="">{{ note.date }}</span>
</div>
</li>
</ul>
</template>
5. 建立筆記內容頁面
- 首先建立一個
pages/[...slug].vue
檔案(catch-all route) - 取得每篇筆記的路徑
- 使用
useAsyncData
和queryContent
方法 - 使用
where
,找到對應當前路徑的筆記檔案
// pages/[...slug].vue
<script setup>
const { path } = useRoute()
const { data } = await useAsyncData(`content-${path}`, () => {
return queryContent().where({ _path: path }).findOne()
})
</script>
- 接著在頁面上使用
<ContentDoc>
或是<ContentRenderer>
來顯示筆記內容
<template>
<main>
<ContentDoc />
</main>
</template>
Code HighLight
- 在
nuxt.config.ts
中,新增content
- 選擇
theme
,例如:github-light
- 參考:shiki Repo
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxt/content'],
content: {
highlight: {
theme: {
// Default theme (same as single string)
default: 'github-light',
// Theme used if `html.dark`
dark: 'github-dark',
// Theme used if `html.sepia`
sepia: 'monokai'
}
}
},
......
在筆記內引入Vue元件
- 在components資料夾內建立
content
資料夾 - 在裡面創建元件
MyCounter
- 到
markdown
檔案內裡面直接引入
// example.md
# 這是計時器
<MyCounter />
- 一個計數元件
Current Count : 0
參考資料
# NuxtContent