在 Vue 2 中,父组件监听子组件的生命周期触发函数主要有以下几种方法:
一、使用 @hook:
语法监听生命周期钩子(最直接)
原理
通过 @hook:生命周期钩子名称
在父组件中直接监听子组件的生命周期事件。
示例代码
<!-- 父组件 Parent.vue -->
<template>
<div>
<ChildComponent
@hook:mounted="onChildMounted"
@hook:beforeDestroy="onChildBeforeDestroy"
/>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
methods: {
onChildMounted() {
console.log('子组件已挂载');
// 可以访问子组件实例:this.$refs.childRef
},
onChildBeforeDestroy() {
console.log('子组件即将销毁');
}
}
}
</script>
支持的钩子
@hook:mounted
@hook:updated
@hook:beforeDestroy
@hook:destroyed
@hook:beforeUpdate
@hook:updated
二、通过子组件自定义事件触发(更灵活)
原理
子组件在生命周期钩子中主动触发自定义事件,父组件监听这些事件。
示例代码
<!-- 子组件 ChildComponent.vue -->
<template>
<div>子组件</div>
</template>
<script>
export default {
mounted() {
this.$emit('child-mounted'); // 触发自定义事件
},
beforeDestroy() {
this.$emit('child-before-destroy');
}
}
</script>
<!-- 父组件 Parent.vue -->
<template>
<div>
<ChildComponent
@child-mounted="onChildMounted"
@child-before-destroy="onChildBeforeDestroy"
/>
</div>
</template>
三、使用 $parent
或事件总线(不推荐)
1. 通过 $parent
直接访问父组件
<!-- 子组件 -->
<script>
export default {
mounted() {
this.$parent.onChildMounted(); // 直接调用父组件方法
}
}
</script>
2. 使用事件总线(Event Bus)
// event-bus.js
import Vue from 'vue';
export const eventBus = new Vue();
// 子组件
import { eventBus } from './event-bus.js';
export default {
mounted() {
eventBus.$emit('child-mounted');
}
}
// 父组件
import { eventBus } from './event-bus.js';
export default {
created() {
eventBus.$on('child-mounted', this.onChildMounted);
},
beforeDestroy() {
eventBus.$off('child-mounted');
}
}
四、使用 $refs
手动调用(需等待子组件挂载)
原理
父组件通过 $refs
获取子组件实例,然后监听子组件的生命周期状态。
示例代码
<!-- 父组件 -->
<template>
<div>
<ChildComponent ref="childRef" />
<button @click="checkChildStatus">检查子组件状态</button>
</div>
</template>
<script>
export default {
methods: {
checkChildStatus() {
// 需确保子组件已挂载
if (this.$refs.childRef) {
console.log('子组件是否已挂载:', this.$refs.childRef._isMounted);
}
}
}
}
</script>
五、对比与选择建议
方法 | 优点 | 缺点 | 适用场景 |
---|---|---|---|
@hook: 语法 |
简洁、无需修改子组件 | 仅限 Vue 2 | 快速监听生命周期 |
子组件自定义事件 | 灵活、语义明确 | 需要修改子组件代码 | 需要传递参数或复杂逻辑 |
$parent 或事件总线 |
无需显式传递事件 | 破坏组件封装性,难维护 | 紧急修复或小型项目 |
$refs |
直接访问子组件实例 | 需要手动管理引用和状态 | 需要频繁操作子组件方法 |
六、注意事项
- 性能考虑:大量使用
@hook:
可能影响性能,建议按需使用。 - 生命周期顺序:父组件监听的钩子在子组件内部钩子之后触发。
- Vue 3 差异:Vue 3 推荐使用组合式 API(如
onMounted
),@hook:
语法仍可用但不常用。