You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt3中用@nuxt/content搜索JSON内容,自定义函数返回空数组求助

Nuxt3中@nuxt/content搜索JSON内容返回空数组问题排查与解决

我在Nuxt3项目中使用@nuxt/content模块搜索JSON文件内容时,调用官方的searchContent函数和自定义搜索函数,两者都返回空数组。以下是相关代码实现及排查解决步骤:

相关代码片段

自定义搜索函数(composable/custom-search-content.ts)

// composable/custom-search-content.ts
export default async function customSearchContent(search: Ref<string>) {
  const runtimeConfig = useRuntimeConfig()
  const { integrity, api } = runtimeConfig.public.content

  const { data } = await useFetch(`${api.baseURL}/search${integrity ? '.' + integrity : ''}.json`)

  const { results } = useFuse(search, data)

  return results
}

nuxt.config.ts配置

// nuxt.config.ts
export default defineNuxtConfig({
 modules: ['@nuxt/content'],
  content: {
    documentDriven: true,
    experimental: {
      search: true
    },
    watch: false
  }
})

JSON文件(content/search.json)

// content/search.json
{
  "title": "Hello Content v2!",
  "textFirst": "first",
  "hello": "hello"
}

组件代码(component.vue)

// component.vue
<script setup lang="ts">
const result = await searchContent('hello');
const result2 = await customSearchContent('hello');
</script>

<template> 
<main>
        <pre>{{ result }} </pre>
        <pre>{{ result2 }} </pre>
</main>
</template>

执行结果

[]
[]

排查与解决步骤

针对官方searchContent函数的问题

  • 检查文档索引状态:开发模式下访问/__content/路由,确认search.json是否被纳入内容模块的文档列表。若开启documentDriven: true,可尝试临时将其设为false,避免文档驱动模式过滤非页面类JSON文件。
  • 明确搜索规则:默认搜索逻辑可能未覆盖目标字段,可指定字段进行精准匹配:
    const result = await searchContent('hello', {
      where: {
        hello: { $contains: 'hello' }
      }
    });
    

针对自定义搜索函数的问题

  • 校验接口返回数据:打印data.value确认useFetch是否正确获取到search.json内容,检查api.baseURL是否为/__content/api(content模块默认API路径)。
  • 适配Fuse.js数据格式:Fuse.js仅支持数组类型数据源,需将单个JSON对象包装为数组,并指定搜索字段:
    const { results } = useFuse(search, data ? [data.value] : [], {
      keys: ['title', 'textFirst', 'hello']
    })
    
  • 修正参数类型不匹配:自定义函数接收Ref<string>类型参数,但调用时传入的是普通字符串,可修改函数参数为字符串类型,或传入Ref对象:
    // 方案1:修改函数参数
    export default async function customSearchContent(search: string) {
      // ...其他代码
      const { results } = useFuse(ref(search), data ? [data.value] : [], { keys: ['title', 'textFirst', 'hello'] })
      return results
    }
    
    // 方案2:传入Ref对象
    const searchQuery = ref('hello')
    const result2 = await customSearchContent(searchQuery);
    

内容的提问来源于stack exchange,提问作者VTsM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:16:20