文件
JSON
如何定义、编写和查询 JSON 数据。
定义集合
content.config.ts
import { defineCollection, defineContentConfig, z } from '@nuxt/content'
export default defineContentConfig({
collections: {
authors: defineCollection({
type: 'data',
source: 'authors/**.json',
schema: z.object({
name: z.string(),
avatar: z.string(),
url: z.string()
})
})
}
})
.json
文件 创建
在 content/authors/
目录下创建作者文件。
{
"name": "Ahad Birang",
"avatar": "https://avatars.githubusercontent.com/u/2047945?v=4",
"url": "https://github.com/farnabaz"
}
{
"name": "Baptiste Leproux",
"avatar": "https://avatars.githubusercontent.com/u/7290030?v=4",
"url": "https://github.com/larbish"
}
data
集合中的每个文件应仅包含一个对象,因此在 JSON 文件中使用顶层数组会导致查询时结果无效。查询数据
现在我们可以查询作者:
<script lang="ts" setup>
// 查找单个作者
const { data: author } = await useAsyncData('larbish', () => {
return queryCollection('authors')
.where('stem', '=', 'larbish')
.first()
})
// 获取所有作者
const { data: authors } = await useAsyncData('authors', () => {
return queryCollection('authors')
.order('name', 'DESC')
.all()
})
</script>