您可以利用父级和子级之间的组件挂钩顺序。当父母
mounted
我们将确保创建并安装所有子组件。
图片来源
here
要执行此操作,可以在父级中定义布尔标志,在装入的挂钩中将此标志更改为true:
import Child1 from "./Child1.vue"
import Child2 from "./Child2.vue"
export default {
name: "Parent",
components: {
child1: Child1,
child2: Child2,
},
data: () => ({
isChildMounted: false
}),
mounted() {
this.isChildMounted = true
}
}
确保将此标志传递给子组件:
<child-2 :isReady="isChildMounted" />
最后,在子组件中,观察道具的变化。当标志更改为true时,我们知道所有子组件都已就绪。是时候发射事件了。
import EventBus from "./EventBus"
export default {
name: "Child2",
props: ['isReady'],
beforeCreate () {
EventBus.$once("MY_EVENT_Y", async () => {
// do something
})
},
watch: {
isReady: function (newVal) {
if (newVal) {
// all child component is ready
EventBus.$emit("MY_EVENT_X")
}
}
}
}