Vue 2.x 中 如何判断子组件是否加载完毕
时间: 2024-02-20 15:02:23 浏览: 45
在 Vue 2.x 中,可以通过监听子组件的 `mounted` 钩子函数来判断子组件是否加载完成。具体实现方法如下:
1. 在父组件中引入子组件并注册:
```javascript
<template>
<div>
<my-component @mounted="onChildMounted" />
</div>
</template>
<script>
import MyComponent from './MyComponent.vue';
export default {
components: {
MyComponent
},
methods: {
onChildMounted() {
console.log('子组件加载完成');
// 在这里可以进行后续操作
}
}
};
</script>
```
2. 在子组件中触发 `mounted` 钩子函数:
```javascript
<script>
export default {
mounted() {
this.$emit('mounted');
}
};
</script>
```
这样就可以在父组件中监听到子组件的 `mounted` 事件,并进行后续操作了。如果子组件很多,你可以在监听到所有子组件都加载完成后再进行后续操作,具体实现方法可以参考以下代码:
```javascript
<template>
<div>
<my-component1 @mounted="onChildMounted" />
<my-component2 @mounted="onChildMounted" />
<my-component3 @mounted="onChildMounted" />
</div>
</template>
<script>
import MyComponent1 from './MyComponent1.vue';
import MyComponent2 from './MyComponent2.vue';
import MyComponent3 from './MyComponent3.vue';
export default {
components: {
MyComponent1,
MyComponent2,
MyComponent3
},
data() {
return {
// 统计加载完成的子组件数量
loadedCount: 0,
// 需要加载的子组件数量
totalCount: 3
};
},
methods: {
onChildMounted() {
this.loadedCount++;
if (this.loadedCount === this.totalCount) {
console.log('所有子组件加载完成');
// 在这里可以进行后续操作
}
}
}
};
</script>
```
这样就可以在所有子组件都加载完成后进行后续操作了。