Vue3父子组件相互调用方法

下面演示均为使用 setup 语法糖的情况!

参考网址:https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose

一、父组件调用子组件方法

子组件需要使用defineExpose对外暴露方法,父组件才可以调用!

1.子组件

	我是子组件



	// 第一步:定义子组件的方法
	const hello = (str: string) => {
		console.log('子组件的hello方法执行了--' + str)
	}
	// 第二部:暴露方法
	defineExpose({
		hello
	})

2.父组件

	
	
	



	import { ref } from 'vue';
	import Child from '../../components/child.vue';

	// 二:定义与 ref 同名变量
	const childRef = ref  ()

	// 三、函数
	const getChild = () => {
		// 调用子组件的方法或者变量,通过value
		childRef.value.hello("hello world!");
	}

3.测试结果

Vue3父子组件相互调用方法

二、子组件调用父组件方法

1.父组件

	



	import Child from '../../components/child.vue';

	const handle = () => {
		console.log('子组件调用了父组件的方法')
	}

2.子组件

	我是子组件
	



	const emit = defineEmits(["sayHello"])

	const say = () => {
		emit('sayHello')
	}

3.测试结果

Vue3父子组件相互调用方法

今天的分享就到这里啦~~

如有错误,欢迎随时雅正。

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/71ce4131c6.html