一篇文章带你简单了解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>
相关推荐
customer089 分钟前
【开源免费】基于SpringBoot+Vue.JS医疗报销系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
道不尽世间的沧桑12 分钟前
第9篇:插槽(Slots)的使用
前端·javascript·vue.js
B站计算机毕业设计超人13 分钟前
计算机毕业设计SpringBoot+Vue.jst房屋租赁系统(源码+LW文档+PPT+讲解)
vue.js·spring boot·后端·eclipse·intellij-idea·mybatis·课程设计
bin915315 分钟前
DeepSeek 助力 Vue 开发:打造丝滑的滑块(Slider)
前端·javascript·vue.js·前端框架·ecmascript·deepseek
杰九40 分钟前
【环境配置】maven,mysql,node.js,vue的快速配置与上手
java·vue.js·spring boot·mysql·node.js·maven
秋意钟1 小时前
Element UI日期选择器默认显示1970年解决方案
前端·javascript·vue.js·elementui
程序员黄同学2 小时前
请谈谈 Vue 中的 key 属性的重要性,如何确保列表项的唯一标识?
前端·javascript·vue.js
繁依Fanyi2 小时前
巧妙实现右键菜单功能,提升用户操作体验
开发语言·前端·javascript·vue.js·uni-app·harmonyos
web182854825122 小时前
nginx 部署前端vue项目
前端·vue.js·nginx
memorycx3 小时前
Vue02
前端·javascript·vue.js