Reputation: 9583
I have a page like this:
<template>
<div class="row flex">
{{posts.id}}
</div>
</template>
<script>
import axios from 'axios'
export default {
async asyncData ({ route }) {
let { data } = await axios.get('http://localhost:8000/api/v1/feeds/' + route.params.id + '/')
return {
posts: data
}
}
}
</script>
When I click link with hot reload (router-link), it display well. But when I reload this window, it appear in 1 seconds and disappear then.
Video: http://g.recordit.co/ht0a0K2X81.gif
How can I fix this?
Upvotes: 2
Views: 8812
Reputation: 15934
Add a property to your data i.e dataLoaded: false
. When your ajax request has finished, set this.dataLoaded = true
. On your template add v-if="dataLoaded
. This will mean the template data won't render until you're ready.
You could also do v-if="posts"
as another way but I generally have a consistent dataLoaded
prop available to do this.
Edit: I just looked at your example again and doing something like this would work:
<template>
<div class="row flex" v-if="posts">
{{posts.id}}
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
posts: null
}
}
methods:{
loadPosts () {
return axios.get('http://localhost:8000/api/v1/feeds/' + this.$route.params.id + '/')
}
},
created () {
this.loadPosts().then(({data}) => {
this.posts = data
})
}
}
</script>
I've removed the async
and just setting posts when the axios
request returns it's promise. Then on the template, it's only showing posts
is valid.
Edit
You can also use your original code and just add v-if="posts"
to the div you have in your template.
Upvotes: 8