How to have list + details pages based on API fetched content

Since your API requires some CORS configuration, here is a simple solution with the JSONplaceholder API of a index + details list collection.

test.vue, pretty much the blog listing in your case

<template>
  <div>
    <div v-if="$fetchState.pending">Fetching data...</div>
    <div v-else>
      <div v-for="item in items" :key="item.id">
        <nuxt-link :to="`/details/${item.id}`"> View item #{{ item.id }}</nuxt-link>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [],
    }
  },
  async fetch() {
    const response = await fetch('https://jsonplaceholder.typicode.com/users')
    this.items = await response.json()
  },
}
</script>

details.vue, this one needs to be into a pages/details/_id.vue file to work

<template>
  <div>
    <button @click="$router.push('/test')">Go back to list</button>
    <br />
    <br />

    <div v-if="$fetchState.pending">Fetching details...</div>
    <div v-else>{{ details.email }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      details: {},
    }
  },
  async fetch() {
    const response = await fetch(`https://jsonplaceholder.typicode.com/users/${this.$route.params.id}`)
    this.details = await response.json()
  },
}
</script>

As you can see, I do only use async/await here and no then for consistency and clarity.

Try this example, then see for fixing the CORS issue. The latter is backend only and not anyhow related to Nuxt. A quick google search may give you plenty of results depending of your backend.

Leave a Comment