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>
// Find a single author
const { data: author } = await useAsyncData('larbish', () => {
return queryCollection('authors')
.where('stem', '=', 'larbish')
.first()
})
// Get all authors
const { data: authors } = await useAsyncData('authors', () => {
return queryCollection('authors')
.order('name', 'DESC')
.all()
})
</script>