一篇文章带你简单了解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>
相关推荐
天天码行空6 小时前
vkeyboardhand:零依赖虚拟键盘指法组件
前端·javascript·vue.js
我要两颗404西柚6 小时前
Stage four:VUE项目上线
前端·javascript·vue.js
TinssonTai9 小时前
Vite 8 版 Chrome 插件全家桶,popup/options/sidepanel 一次集齐
前端·vue.js
sugar__salt10 小时前
Vue3 自定义指令与插槽(Slot)技术详解
前端·javascript·vue.js·前端框架·vue
英勇无比的消炎药11 小时前
TinyRobot DropdownMenu 下拉菜单:三种触发方式与实现原理
vue.js
zhedream11 小时前
a-select / a-input 自定义下拉、Vue2 Fragment ,以及 transfer-dom
前端·vue.js
无人生还11 小时前
从 Vue3 到 React · 快速上手系列第 10 篇:路由
前端·vue.js·react.js
rememberme00111 小时前
华为云 CodeArts Pipeline前端 Vue 项目自动打包发布配置指南
前端·vue.js·华为云
A242073493012 小时前
Vue.js 初学者注意事项与项目开发实践指南
前端·javascript·vue.js
90后的晨仔1 天前
从 H5 到 uni-app:一篇写给前端小白的"翻译指南"
前端·vue.js·前端框架