一篇文章带你简单了解Vue3父子组件如何相互调用方法

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

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

1.子组件

js 复制代码
<template>
	<div>我是子组件</div>
</template>
 
<script lang="ts" setup>
	// 第一步:定义子组件的方法
	const hello = (str: string) => {
		console.log('子组件的hello方法执行了--' + str)
	}
	// 第二部:暴露方法
	defineExpose({
		hello
	})
</script>

2.父组件

js 复制代码
<template>
	<button @click="getChild">触发子组件方法</button>
	<!-- 一:定义 ref -->
	<Child ref="childRef"></Child>
</template>
 
<script lang="ts" setup>
	import { ref } from 'vue';
	import Child from '../../components/child.vue';
 
	// 二:定义与 ref 同名变量
	const childRef = ref <any> ()
 
	// 三、函数
	const getChild = () => {
		// 调用子组件的方法或者变量,通过value
		childRef.value.hello("hello world!");
	}
</script>

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

使用defineEmits

1.父组件

js 复制代码
<template>
	<Child @sayHello="handle"></Child>
</template>
 
<script lang="ts" setup>
	import Child from '../../components/child.vue';
 
	const handle = () => {
		console.log('子组件调用了父组件的方法');
	}
</script>

2.子组件

js 复制代码
<template>
	<div>我是子组件</div>
	<button @click="say">调用父组件的方法</button>
</template>
 
<script lang="ts" setup>
	import { defineEmits } from 'vue';

	const emit = defineEmits(["sayHello"]);
 
	const say = () => {
		emit('sayHello');
	}
</script>
相关推荐
逸铭30 分钟前
Day 5:三栏布局——左账号 / 中聊天 / 右工具
vue.js·electron
用户1733598075371 小时前
Vue 3 SPA 首屏优化:从 3s 到 1.2s 的 5 个实践
前端·vue.js
锋行天下19 小时前
我试图优化 Vite 的拆包,结果首屏慢了 10 倍
前端·vue.js·架构
ZhengEnCi1 天前
Q02-Vue-React-index.html完全指南
vue.js·react.js·html
晴虹1 天前
vue3-scroll-more:横向滚动条-元素或页签过多滚动显示处理的组件
前端·vue.js
Forever7_1 天前
尤雨溪转发:Vue-tui 0.1 发布!Vue 终于杀进终端!
vue.js
dkbnull1 天前
Vue 虚拟 DOM Diff 算法与 key 机制原理
vue.js
前端切图崽_小郭2 天前
虚拟滚动:静态 vs 动态的核心差异与实现?
vue.js
白鲸开源2 天前
Apache SeaTunnel Zeta Engine 的 Basic Auth 是怎么工作的?
java·vue.js·github
卤蛋fg62 天前
vue 甘特图 vxe-gantt 的使用(四):周视图的渲染
vue.js