Home > database >  Nuxt.js : Dynamically fetching data from content folder
Nuxt.js : Dynamically fetching data from content folder

Time:08-22

I'm trying to fetch for each category, A, B,C a different folder in my content folder.

The best way I've managed to do that is using v-for and some arrays list in order to have my category list at the same place. This array works with slotsthat generate a new Item for each new element :

 <div v-for="accordion in accordions" :key="accordion.title" >
      <Item>
        <template #title>
          {{ accordion.title }}
        </template>

        <template #content>
          <div>{{ accordion.text }}</div>
        </template>
      </Item>
    </div>
  </div>

I have this to fetch my articles :

  async asyncData ({ $content }) {
    const articles = await $content('', { deep: true })
      .only(['title', 'description', 'img', 'slug', 'cat'])
      .sortBy('createdAt', 'asc')
      .fetch()

    return { articles }
  }, // this fetch all of my articles, which is nice

Now, in the accordions, I would like to do something similar to this : (or find a way to pass a .where({ cat: 'A' })...)


 accordions: [
        {
          title: 'A',
          text: const products = await this.$content('text').where({ 'articles.cat': { $contains: 'A' } }).fetch()
        },
        {
          title: 'B',
          text: const products = await this.$content('text').where({ 'articles.cat': { $contains: 'B' } }).fetch()
        },
        {
          title: 'C',
          text: const products = await this.$content('text').where({ 'articles.cat': { $contains: 'C' } }).fetch()
        }
      ],

How can I manage to instead of hardcoded text, have my articles from my content folder ?

Supposed render

CodePudding user response:

This gives a nice result (with some random .md files but the same structure as yours).

<template>
  <pre>{{ articles }}</pre>
</template>

<script>
export default {
  async asyncData ({ $content }) {
    const articles = await $content('', { deep: true })
      .only(['title', 'description', 'img', 'slug'])
      .sortBy('createdAt', 'asc')
      .fetch()

    return { articles }
  }
}
</script>

The result displayed being

enter image description here

  • Related