【发布时间】:2019-09-23 18:19:40
【问题描述】:
父组件:
<template>
<div>
<Nav :data="data" />
</div>
</template>
<script lang="ts">
// ... removed obvious imports for readability
@Component({
components: {
Nav: () => import('@/components/Nav.vue')
}
})
export default class Home extends Vue {
public nav: NavInterface = {}
private getData(): Promise<any> {
// ... this.$http - is an axios instance
return this.$http
.getData()
.then((resp: any) => {
this.data = resp.data.nav
})
}
}
</script>
子组件:
<template>
<div class="nav">
<ul>
<li v-for="(nav, index) in data">{{ nav.id }}</li>
</ul>
</div>
</template>
<script lang="ts">
// ... imports
export default class Nav extends Vue {
@Prop({ default: null }) public readonly data!: NavInterface
private mounted(): void {
console.log(this.data) // is undefined, because promise is not resolved yet - this is a problem
}
}
</script>
有一个问题,当一个 Promise 在父组件中解析时,它不会在子组件中解析。只有在我的getData() 承诺成功解决后,是否可以加载子组件,因为如果没有来自父级的数据,我的子组件就没有意义。
当然,我可以在子组件中使用观察者,然后,我会从承诺中获得正确的数据,但对我来说似乎很麻烦:
@Watch('data')
private onPropChange(val: any) {
console.log(val) // i get the correct data
}
我更喜欢有条件地渲染我的子组件,只有在 promise 解决之后。
【问题讨论】:
标签: javascript typescript vue.js