I've been working on implementing dynamic components in Vue.js, but I'm having trouble figuring out how to display the component only after it has fetched its data. Until then, it should show the previous component.
Here's the scenario: When the page initially loads, it displays the Home component. Then, when I click on "Show posts", nothing should happen until the Posts component has successfully fetched its posts. Only then should the Posts component be displayed. I don't want any loading indicators to appear.
I could fetch the posts in my Home component, but I believe that responsibility should lie with the Posts component. Additionally, if there are many components, I prefer for each one to handle fetching its own data. Is this achievable?
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()
{
// Display Posts component ONLY after it has fetched its 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
})
},
}