Main component:
<template>
<div>
<Nav :data="data" />
</div>
</template>
<script lang="ts">
// ... imports removed for clarity
@Component({
components: {
Nav: () => import('@/components/Nav.vue')
}
})
export default class Home extends Vue {
public nav: NavInterface = {}
private getData(): Promise<any> {
// ... this.$http - using axios instance
return this.$http
.getData()
.then((resp: any) => {
this.data = resp.data.nav
})
}
}
</script>
Sub-component:
<template>
<div class="nav">
<ul>
<li v-for="(nav, index) in data">{{ nav.id }}</li>
</ul>
</div>
</template>
<script lang="ts">
// ... imports removed for brevity
export default class Nav extends Vue {
@Prop({ default: null }) public readonly data!: NavInterface
private mounted(): void {
console.log(this.data) // Returns undefined because promise is not resolved yet
}
}
</script>
A challenge arises when the promise resolves in the parent component before propagating to the child one. Is there a way to only load the child component after successful resolution of the getData()
promise since the child component relies on the parent's data?
One approach could involve utilizing a watcher in the child component but it feels like a workaround:
@Watch('data')
private onPropChange(val: any) {
console.log(val) // Correct data becomes available
}
I would rather conditionally render my child component only after the promise has been fulfilled.