【问题标题】:Dynamic Nuxt content fetching depending of the path根据路径获取动态 Nuxt 内容
【发布时间】:2021-10-30 05:53:25
【问题描述】:

我的 nuxt 项目中有一个这样的文件夹结构:

...
/pages/_slug.vue
/content
  /report
    page1.json
    /doc
      page2.json

在我的页面文件夹中,我有一个 _slug.vue 文件

<template>
  <div>{{ profile.hello }}</div>
</template>

<script>
export default {
  async asyncData ({ $content, params }) {
    const profile = await $content('report', params.slug, { deep: true }).fetch()
    return { profile }
  }
}
</script>

当我访问/page1 时,一切正常,但是当我请求/doc/page2 时,没有呈现任何页面。现在我很困惑,因为我添加了{ deep:true } 来实现这种行为,但这不起作用。如何确保文件夹结构与我的路由相似?

【问题讨论】:

  • 当你在/doc/page2时,params.slug的内容是什么?应该是'page2' 还是'/doc/page2'?
  • 应该是'/doc/page2'

标签: nuxt.js nuxt-content


【解决方案1】:

如果你设置pages/_.vue并将这个内容写入其中,它应该可以正常工作

<template>
  <div>{{ profile.hello }}</div>
</template>

<script>
export default {
  async asyncData({ $content, route }) {
    const profile = await $content('report', route.fullPath, { deep: true }).fetch()
    return { profile }
  },
}
</script>

由于Unknown Dynamic Nested Routes 的使用,这有效。


此解决方案使用$content('articles', params.slug) 的以下模式并将其转换为/articles/${params.slug},如documentation 部分所示。

【讨论】:

  • 如果我的内容 json 文件总是相同的,比如说 page.json,我该如何修改它以便在 / 我看到 report/page.json 和 /doc report/doc/page .json?
  • @JeremyKnees 条件/swtich 后跟params.slug 的插值是解决此问题的好方法。
  • 实际上,我正在寻找的解决方案只需要一个$content('report', route.fullPath, 'page', { deep: true }).fetch()。不管怎么说,还是要谢谢你!你帮了很多忙:)
  • @JeremyKnees 嗯,不知道。很好的发现!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-07
  • 2019-05-28
  • 2015-11-01
相关资源
最近更新 更多