Vue 父组件监听子组件生命周期
三种方法实现父组件监听子组件生命周期钩子
问题
Vue 中父组件如何监听子组件的生命周期?
解答
Vue 父组件不能直接监听子组件的生命周期钩子,但可以通过以下三种方法间接实现。
方法一:事件通信
子组件在生命周期钩子中触发自定义事件,父组件监听该事件。
子组件:
<template>
<div>子组件</div>
</template>
<script>
export default {
name: 'ChildComponent',
mounted() {
this.$emit('childMounted');
}
}
</script>
父组件:
<template>
<div>
<ChildComponent @childMounted="handleChildMounted" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleChildMounted() {
console.log('子组件已挂载');
}
}
}
</script>
方法二:使用 ref
父组件通过 ref 访问子组件实例,在父组件生命周期中调用子组件方法。
子组件:
<template>
<div>子组件</div>
</template>
<script>
export default {
name: 'ChildComponent',
mounted() {
console.log('子组件已挂载');
}
}
</script>
父组件:
<template>
<div>
<ChildComponent ref="child" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
mounted() {
console.log('访问子组件实例:', this.$refs.child);
}
}
</script>
方法三:使用 @hook 监听器
Vue 提供了 @hook: 语法,可以直接监听子组件的生命周期钩子。
<template>
<div>
<ChildComponent
@hook:mounted="handleChildMounted"
@hook:updated="handleChildUpdated"
/>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleChildMounted() {
console.log('子组件已挂载');
},
handleChildUpdated() {
console.log('子组件已更新');
}
}
}
</script>
关键点
- 事件通信方式需要在子组件中手动触发事件,适合需要传递数据的场景
- ref 方式可以直接访问子组件实例和方法,但耦合度较高
@hook:语法最简洁,无需修改子组件代码,推荐使用- 所有生命周期钩子都可以通过
@hook:hookName监听
目录