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.
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.