vue.jsnuxt.jsnuxt-content

Nuxt-content not working with asyncData in a component


I'm trying to fetch content from my content/blog folder but I can't make it work in the components/menu.vue page since it's a component ?

This is working in the page/index.vue but not in components/menu.vue. Why?

I'm new to all this and maybe I'm doing something wrong here, maybe I'm not able to fetch content from a component... I don't know.

<template>
  <div class="container">
    <div class="articles">
          <div class="article" v-for="article of articles" :key="article">
            <nuxt-link :to="{ name: 'slug', params: { slug: article.slug } }">
              <div class="article-inner">
                <img :src="require(`~/assets/${article.img}`)" alt="" />
                <div class="detail">
                  <h3>{{ article.title }}</h3>
                  <p>{{ article.description }}</p>
                </div>
              </div>
            </nuxt-link>
          </div>
     </div>
  </div>
</template>

<script>
export default {
  async asyncData ({ $content, params }) {
    const articles = await $content('blog', params.slug)
      .only(['title', 'description', 'img', 'slug'])
      .sortBy('createdAt', 'asc')
      .fetch()
    console.log('bongo')
    return {
      articles
    }
  },
  data () {
    return {
      num: this.$route.name
    }
  },
  computed: {
    currentRouteName () {
      return this.$route.name
    }
  }
}
</script>

Solution

  • As written here: https://nuxtjs.org/docs/features/data-fetching#async-data

    asyncData is only available for pages and you don't have access to this inside the hook.

    So yes you can use asyncData only in a page.
    An alternative would be to use a non-blocking fetch() hook as shown here: https://nuxtjs.org/docs/features/data-fetching#accessing-the-fetch-state