使用Nuxt Content查询Nuxt 3中的JSON数组



如何在Nuxt 3和Nuxt Content中查询单个元素的JSON数组?

├── @nuxt/content@2.3.0
└── nuxt@3.0.0

content/people.json

[
{
"name": "Name1",
"id": 1
},
{
"name": "Name2",
"id": 2
}
]

查询所有人的数据结果如下:

[
{
"_path": "/people",
"_dir": "",
"_draft": false,
"_partial": false,
"_locale": "en",
"body": [
{
"name": "Name1",
"id": 1
},
{
"name": "Name2",
"id": 2
}
],
"_id": "content:people.json",
"_type": "json",
"title": "People",
"_source": "content",
"_file": "people.json",
"_extension": "json"
}
]

pages/people/[id].vue

<template>
<pre>{{ data }}</pre>
</template>
<script setup>
const route = useRoute();
const id = route.params.id;
const data = await queryContent("people")
.where({ id }) // **What should this be? I can't seem to get any variants to work**
.findOne();
</script>

我可以在索引页面上查询所有人。然而,我现在想得到单曲";人;在[id].vue页面上的JSON数组中,但我不知道如何在Nuxt Content中使用where子句查询此文档。

在我看来,这个问题源于对where()子句功能的误解。根据nuxt内容文档的此子句用于按查询筛选结果。这意味着结果来自nuxt应用程序的content目录,而不是每个文件内的内容。它过滤文件和文件夹,而不是其中的内容。例如,当我们说const { data } = await useAsyncData('list', () => queryContent('/list').where({ title: 'list1 page' }).findOne());时,我们希望过滤content/list目录中的文件,并找到具有title: 'list1 page'的文件。我们无法过滤或更改例如list1.mdlist1.json中的内容,或者。。。使用where()子句的文件。

对于这个问题,我认为我们有两个选择:

  • 第一个是我们在从queryContent(不使用where())获得结果后,借助纯JavaScript(例如使用filter()方法)对people/[id].vue文件中的结果进行过滤,以根据id数据获得人员信息。

  • 我认为第二种选择更好,因为允许我们从nuxt内容特性和功能中获益的是更改数据结构。要做到这一点,我们必须在content目录中创建一个名为people的文件夹。然后在里面我们创建1.person1.json2.person2.json等文件。在每个文件里,我们都有特定人的json数据,如下代码所示:

    {"name":"Name1";,"id":1.}

    然后,使用pages/people/[id].vue文件中的类似代码,您可以根据每个人的id自动访问该人的数据:

<template>
<div>
<p>{{ $route.params.id }}</p>
</div>
</template>
<script setup>
const route = useRoute();
console.log(route.params.id);
const { data } = await useAsyncData('people', () => queryContent('people', "person"+ route.params.id).findOne());
console.log(data.value.name);
</script>

正如您所看到的,在第二个选项中,我们根本不需要使用where()子句,因为不断变化的数据结构使过滤过程变得更好、更容易。

最新更新