Reputation: 345
I'm working a static vue website fetching data with the wordpress rest api.
I'm trying to display the data I fetch on a API on the vue page :
<template>
<div>
<h1>
{{ title }}
</h1>
<template>
{{ content }}
</template>
<p><nuxt-link to="/">Back to home page</nuxt-link></p>
</div>
</template>
<script>
import axios from 'axios'
export default {
validate({ params }) {
return isNaN(+params.slug)
},
asyncData({ params, error }) {
let slug = params.slug;
// We can return a Promise instead of calling the callback
return axios.get('https://dev.lesdeuxvagues.com/api/wp-json/wp/v2/posts/?slug='+slug)
.then((res) => {
return { data: res.data }
})
},
}
</script>
I also tried this way :
<template>
<div>
<h1>
{{ title }}
</h1>
<template>
{{ content }}
</template>
<p><nuxt-link to="/">Back to home page</nuxt-link></p>
</div>
</template>
<script>
import axios from 'axios'
export default {
validate({ params }) {
return isNaN(+params.slug)
},
async asyncData({ params, error }) {
try {
let slug = params.slug;
const { data } = await axios.get(`https://dev.lesdeuxvagues.com/api/wp-json/wp/v2/posts/?slug=`+slug)
return data
} catch (e) {
error({ message: 'Article not found', statusCode: 404 })
}
}
}
</script>
but neither of the two solutions work...
I think the problem is coming from the async function, but I didn't get why..
Thanks in advance for your help
Upvotes: 0
Views: 233
Reputation: 1498
This is what you may want to try. Of course, you can customize your API with your convenience.
<template>
<p>
{{data}}
</p>
</template>
<script>
import axios from 'axios'
export default {
asyncData(context) {
// We can return a Promise instead of calling the callback
return axios.get('https://dev.lesdeuxvagues.com/api/wp-json/wp/v2/posts/')
.then((res) => {
return {
data: res.data[0]
}
})
},
}
</script>
Upvotes: 3