Showing a collection of articles on a webpage using Nuxt/content - Step by step guide

I have implemented the nuxt/content module to establish a documentation website.

In a recent post on the Nuxt blog, they demonstrated displaying content in a separate index.vue page and post details on the _slug.vue page.

My goal is to present a list of articles/posts on the same page using a distinct layout.

Below is the folder structure I have set up:

content (folder)
    articles (folder)
        article1.md
        article2.md
        article3.md
pages (folder)
    blog (folder)
        _slug.vue
        index.vue

Here is the content of my_slug.vue file:

<template>
  <div class="flex">
    <aside class="w-1/3">
      <ul>
        <li v-for="article in articles" :key="article.slug">
          <NuxtLink :to="{ name: 'blog-slug', params: { slug: article.slug } }">
            <div>
              <h2>{{ article.title }}</h2>
            </div>
          </NuxtLink>
        </li>
      </ul>
    </aside>
    <main class="w-full">
      <h1>{{ article.title }}</h1>

      <p>Article last updated: {{ formatDate(article.updatedAt) }}</p>

      <nuxt-content :document="article" />

      <prev-next :prev="prev" :next="next" />
    </main>
    <aside class="w-1/3">
      <h4>On this page</h4>
      <nav>
        <ul>
          <li v-for="link of article.toc" :key="link.id">
            <NuxtLink :to="`#${link.id}`" :class="{ 'py-2': link.depth === 2, 'ml-2 pb-2': link.depth === 3 }">{{ link.text }}</NuxtLink>
          </li>
        </ul>
      </nav>
    </aside>
  </div>
</template>

<script>
  export default {

      async asyncData({ $content, params }) {
        const articles = await $content('articles', params.slug)
          .only(['title', 'slug'])
          .sortBy('createdAt', 'asc')
          .fetch()

        const article = await $content('articles', params.slug).fetch()

        const [prev, next] = await $content('articles')
          .only(['title', 'slug'])
          .sortBy('createdAt', 'asc')
          .surround(params.slug)
          .fetch()

        return {
          articles,
          article,
          prev,
          next
        }
      },
    methods: {
      formatDate(date) {
        const options = { year: 'numeric', month: 'long', day: 'numeric' }
        return new Date(date).toLocaleDateString('en', options)
      }
    }
  }
</script>

When I include the "Display all articles" code snippet on the index.vue page, it functions correctly. However, when both are integrated on the _slug.vue page, the list appears empty.

Here is the index page where the posts are displayed correctly:

<template>
   <div>
    <h1>Blog Posts</h1>
    <ul>
      <li v-for="article of articles" :key="article.slug">
        <NuxtLink :to="{ name: 'blog-slug', params: { slug: article.slug } }">
          <div>
            <h2>{{ article.title }}</h2>
          </div>
        </NuxtLink>
      </li>
    </ul>
  </div>
</template>

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

      return {
        articles
      }
    }
  }
</script>

<style>

</style>

Can someone help me figure out what I might be overlooking?

Answer №1

Your search query did not return any articles as it is incorrect; please make sure to search within the articles folder:

const articles = await $content('articles') // instead of $content('articles', params.slug)
  .only(['title', 'slug'])
  .sortBy('createdAt', 'asc')
  .fetch()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Need jQuery solution for changing CSS in numerous locations upon hover

Currently, I am working on a WordPress website and I am trying to figure out how to change the CSS color of a side navigation element when a remote image is hovered over. In a typical scenario, I would accomplish this using CSS by assigning a hover class ...

Having trouble getting past the "Starting metro bundler" step when using the 'expo start' or 'npm start' command?

Currently, I am using React Native Expo to develop a mobile application. The process I followed includes the following steps: expo init myapp cd myapp expo start Initially, everything was running smoothly after executing these three commands. However, as ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...

js include exclude switch a category

Although this question has been asked before, I have a query on completely removing an "id" from an element. Let's consider the following scenario: <div id="page"> some content here </div> I want to eliminate the "id" attribute from the ...

The requested file cannot be accessed using XMLHttpRequest.open url

Currently, I am in the process of learning about AJAX by following the MDN tutorial. However, I have encountered an issue with the first sample code provided to fetch test.html. Regardless of whether I use absolute or relative paths, my local server consis ...

Using AJAX, JQuery, and PHP to convert a given name to match the columns in a query, utilizing the data sent

One thing that I'm wondering about is how PHP handles my ajax requests. For example, consider the following code snippet: $("#addUser").on('click', '.btnAddSubmitFormModal', function() { $.post("add.php", { ...

Executing Nuxt middleware on the client-side post static rendering

We are transitioning from using a Single Page Application to statically generated pages, but we are encountering an issue with middleware. Essentially, when Nuxt is statically rendered, the middleware runs on the build server first and then runs again aft ...

Is the use of Youtube API with an unaffiliated laborer

What an unusual situation! I've implemented the YouTube JavaScript API to display a playlist on my website, but upon checking how things were operating in my workers, it appears that the API is directing its messages to an unexpected location. The da ...

Why are the HTML links generated by JS not opening in Chrome?

<a href='http://www.xyz.hu/xyz' alt='Kosár' title='Kosár'>Megtekintés</a> Additionally: - A setInterval function refreshes the sibling's content every second, although it should not affect this specific el ...

A guide on how to reset Orbit Controls once the target has been defined

After clicking the mouse, I successfully set a new target for my THREE.OrbitControls and it works perfectly. However, once the camera pans to the new location, I lose all mouse interaction. I suspect that I may have broken the controls when I made the came ...

Tips for preloading a small placeholder image before the main content is loaded

After browsing , I noticed an interesting image loading style. The website initially shows a patterned image before revealing the actual content. This method creates visually appealing content while waiting for the entire webpage to load. Upon inspecting ...

Updating the value of a v-text-field in Vuetify

What is the best way to modify input values? Here is an example: `https://jsfiddle.net/mbqjp4ax/` If a number entered is greater than 5, the system should automatically input the number 9 instead. While this works correctly when entering numbers greater ...

Tips for removing markers from personal Google Maps

I am having trouble deleting markers from my Google Maps using my code. The markers array seems to be empty even after adding markers. Can anyone help me troubleshoot this? Thank you! When I use console.log(markers.length) in the removeMarkers() function, ...

Verify the user's activity status in the MySQL database using Node.js by checking the timestamp of their last login

I have a query regarding user activity and deletion from the database. I need to determine when a user last logged in to see if their account is inactive. Unfortunately, I am unsure of how to tackle this task or check for the last login time. If anyone c ...

Class with an undefined function call

Currently, I am working with angular2 and TypeScript where I have defined a class. export class Example{ //.../ const self: all = this; functionToCall(){ //.. Do somerthing } mainFunctionCall(){ somepromise.then(x => self.fu ...

Sharing Axios Response Data in VueJS: A Guide for Parent-Child Component Communication

Can someone please help me with using VueJS and Axios to retrieve API data and pass it to multiple child components? I am trying to avoid accessing the API multiple times in the child components by passing the data through props. The issue I am facing is ...

Generating an Array of objects through the use of the each method

Currently, I am in the process of developing a web scraper using node.js along with puppeteer and cheerio. Although I can successfully display the desired strings in the console.log, I am facing challenges in determining if this task is achievable. $(&apo ...

Encountering an endless loop while attempting to retrieve data from Firebase in Next.js through the use of useEffect

Currently, I am in the process of setting up a video section for a project using NextJS. The videos are stored in firebase storage. I have implemented a dynamic route that retrieves all videos from a specific reference within the bucket. For instance, if ...

Click event not triggering on a div component in React

I'm having an issue with an onclick event on a div that is not triggering. <div className={styles.scrollingDiv}> <div className={styles.rectangleDiv} /> <div className={styles.menuBarDiv}> ...

AngularJS: The delay in updating variable bindings following a REST API call

When utilizing a REST service, I wanted to implement a variable to show whether the service is currently loading or not. Controller $scope.loading = true; $http.get('/Something'). success(function(data, status, headers, config) ...