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

Nuxt根据路径动态获取content内容 嵌套路由匹配失败如何解决

问题原因
  • 路由匹配规则不匹配:你当前使用的单级动态路由_slug.vue仅支持匹配单段路径,/page1属于单段路径可正常命中,而/doc/page2是两段路径,路由无法匹配到该页面组件,因此无渲染内容。
  • $content调用逻辑有误:{ deep: true }参数的作用是递归查询指定目录下的所有嵌套文件,并非用于拼接多级路径,按精确路径查询内容时不需要添加该参数。
解决方法

方案1:适配任意深度嵌套路径(推荐)

  1. 重命名页面文件:将/pages/_slug.vue修改为/pages/_.vue,这是Nuxt约定的全匹配动态路由,可捕获任意深度的路径,完整路径会自动存入params.pathMatch变量。
  2. 修正asyncData逻辑:
<template>
  <div>{{ profile.hello }}</div>
</template>

<script>
export default {
  async asyncData ({ $content, params }) {
    // 访问/page1时params.pathMatch为'page1',访问/doc/page2时为'doc/page2'
    const profile = await $content('report', params.pathMatch).fetch()
    return { profile }
  }
}
</script>

方案2:固定层级嵌套路径

如果你的内容层级固定为最多2级,也可以用嵌套动态路由实现:

  1. 新建目录结构:/pages/_category/_slug.vue
  2. 对应asyncData写法:
async asyncData ({ $content, params }) {
  const profile = await $content('report', params.category, params.slug).fetch()
  return { profile }
}
deep参数适用场景

当你需要在指定目录下递归搜索符合条件的文件时才需要使用deep参数,示例:

// 递归查询report目录下所有slug等于当前参数的文件
const profile = await $content('report', { deep: true }).where({ slug: params.slug }).fetchOne()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:42:03