Search code examples
vue.jsnuxt.jsnuxt-content

Nuxt Content async fetch in component


I'm new to the @nuxt/content module and it's working well except within components.

Here I'm trying to get the content like so:

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 }
  },
}

How can I use content within components?


Solution

  • So, there is no reason that $content will not work in components, I double-checked. It's just the way fetch works in comparison to asyncData.

    You can read more about the differences here: https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12/#asyncdata-vs-fetch

    But it comes down to a different syntax when using the fetch hook, as follows:

    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
      },
    }