Template in Nuxt.js

Hi everyone,

I’m trying to use the API locally to pull my blog posts in a Nuxt project, following this guide

import GhostContentAPI from '@tryghost/content-api'
const api = new GhostContentAPI({
  url: 'http://localhost:2369',
  key: '22444f78447824223cefc48062',
  version: 'v2'
})

// fetch 5 posts, including related tags and authors
api.posts
  .browse({ limit: 5, include: 'tags,authors' })
  .then(posts => {
    posts.forEach(post => {
      console.log(post.title)
    })
  })
  .catch(err => {
    console.error(err)
  })

This code works fine, and in the console I can see the 5 post titles.
However, how can I use that data in my template? I need to do something like this:

<article v-for="post in posts" :key="post">
  <h2>{{ post.title }}</h2>
</article>

but ‘posts’ doesn’t seem to be available apart from inside the promise, and I am not sure how to pass the variable.

Any help? Thanks

Hey!

Promises are a way to handle asynchronous values, the reason that you can’t access the value apart from “inside the promise” is because the code outside of it has executed already by the time the promise resolved with the value.

I would recommend reading up and becoming a little more familiar with promises - here is a good chapter of a book on them: 25. Promises for asynchronous programming

If you just want to dive in though, the Nuxt.js framework has this small page on async data, which you might find useful.

You could probably use it like

import GhostContentAPI from '@tryghost/content-api'
const api = new GhostContentAPI({
  url: 'http://localhost:2369',
  key: '22444f78447824223cefc48062',
  version: 'v2'
})

export default {
  asyncData ({ params }) {
    return api.posts.browse({ limit: 5, include: 'tags,authors' })
  }
}

Hope this helps a little, good luck and have fun :smile:

2 Likes

Hi fabien, thanks for your quick reply!

You’re right, I need to read about promises and learn how they works, to understand them more than just “use” them!

However, your example did work!
To get “posts” in the template, I also replaced the console.log:

.then(posts => {
  posts.forEach(post => {
    console.log(post.title)
  })
})

with just:

.then(posts => {
  return {
    posts
  }
})

(copying it here in this basic way, just in case someone else like me it’s looking for it!)

Thanks again and take care!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.