vue中父组件监听子组件生命周期

文章类型:Vue

发布者:hp

发布时间:2023-08-01

在实际开发过程中,有时候父组件需要监听下子组件里面的生命周期,今天,整理一下方案

一:方案

1:采用emit方式传递

A:通过子组件$emit方式提交,父组件绑定一个方法实现监听

	<cs @mounted="sonMounted"></cs>
	mounted() {
			console.log('123456')
			this.$emit('mounted','子组件mounted触发')
		}

B:完整代码

//子组件
<template>
	<view>{{msg}}</view>
</template>

<script>
	export default {
		data(){
			return{
				msg:'123456'
			}
		},
		mounted() {
			console.log('123456')
			this.$emit('mounted','子组件mounted触发')
		}
	}
</script>

<style>
</style>
//父组件
<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<cs @mounted="sonMounted"></cs>
		</view>
	</view>
</template>

<script>
	import cs from '../../components/cs.vue'
	export default {
		components:{
		cs	
		},
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {

		},
		methods: {
		sonMounted(data){
			console.log('触发')
			console.log(data)
		}
		}
	}
</script>

2:hook简写方式,子组件不需要$emit

<cs @hook:mounted="sonMounted"></cs>
    mounted() {
			console.log('123456789')
		}

二:总结

1:微信小程序不适用方案二,会监听不到!!!

2:hook方式可以监听created等生命周期

3:子组件的mounted比父组件的mounted先触发

4:方案一$emit每次手动发布,而hook方式是自动发布监听