【问题标题】:Nuxt Content async fetch in component组件中的 Nuxt 内容异步获取
【发布时间】:2021-06-02 03:22:56
【问题描述】:

我是@nuxt/content module 的新手,除了在组件内之外,它运行良好。

我在这里尝试获取这样的内容:

layout.vue

export default {
  name: 'Default',
  CONTENT: 'content',
  async asyncData({ $content }) {
    const content = await $content('content').fetch()
    return { content }
  },
}

component.vue

export default {
  async fetch({ $content }) {
    this.content = await this.$content('content', { deep: true }).fetch()
  },
  data() {
    return { content }
  },
}

如何在组件中使用内容?

【问题讨论】:

  • 第一注!你不能在你的布局中使用asyncDataasyncData 仅在页面中可用,而不是在组件或布局中。

标签: vue.js nuxt.js nuxt-content


【解决方案1】:

所以,$content 没有理由不能在组件中工作,我仔细检查了。这就是 fetchasyncData 相比的工作方式。

您可以在此处阅读有关差异的更多信息:https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12/#asyncdata-vs-fetch

但是当使用fetch 钩子时,它归结为不同的语法,如下所示:

export default {
  data() {
    return {
      content: [],
    }
  },
  async fetch({ $content }) {
    this.content = await $content('content', { deep: true }).fetch()
    // ! it's $content and not this.$content here since you've imported it in the scope
  },
}

【讨论】:

  • 请不要在评论中打印那种代码。使用新代码/结果编辑和格式化您的答案。
  • wups :) 所以它现在可以工作了!
  • 没问题,很高兴它有效。欢迎来到 StackOverflow 并享受您的 Nuxt ! :)
  • 这在 2.15 版本上对我不起作用。我不得不使用:async fetch() { this.$content(); }
  • @OsvaldoMaria 要么解构它,要么调用 this 我猜。
猜你喜欢
  • 2021-08-17
  • 2022-08-13
  • 2022-10-18
  • 2022-08-22
  • 2021-07-23
  • 1970-01-01
  • 2021-09-24
  • 2012-09-07
  • 2021-09-20
相关资源
最近更新 更多