I am implementing Vue.js dynamic components but I can't seem to figure out how to show the component only when it has fetched it's data. Until then it should show the old component.
The scenario is this. When the page is loaded it should show the Home component. Then I click on "Show posts". Nothing should happen until the Posts component has fetched it's posts. Then it should show the Posts component. I don't want any loading to show.
I could fetch posts in my Home compoent but I think the Posts component should be responsible for that. Also if I have many components I don't want to fetch all their data in my Home component. They should fetch their own data (I think). Is this possible to do?
home.js
import Home from './home.js'
import Posts from './posts.js'
export default {
template: `
<div>
<a @click="showPosts">Show posts</a>
<component :is="currentComponent" />
</div>
`,
methods:
{
showPosts()
{
// Do this ONLY after the Posts component has fetched it's data... not immediately...
this.currentComponent = Posts
}
},
data:
{
currentComponent: Home
},
}
posts.js
export default {
template: `
<div>
<div v-for="post in posts">{{ post.body }}</div>
</div>
`,
data:
{
posts: [],
},
created()
{
axios.get('/posts').then(({ data } => {
this.posts = data
})
},
}