一篇文章带你简单了解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>
相关推荐
程序员大金7 分钟前
基于SpringBoot+Vue+MySQL的在线学习交流平台
java·vue.js·spring boot·后端·学习·mysql·intellij-idea
qq_25183645714 分钟前
基于SpringBoot vue 医院病房信息管理系统设计与实现
vue.js·spring boot·后端
一 乐2 小时前
租拼车平台|小区租拼车管理|基于java的小区租拼车管理信息系统小程序设计与实现(源码+数据库+文档)
java·数据库·vue.js·微信·notepad++·拼车
寻找09之夏6 小时前
【Vue3实战】:用导航守卫拦截未保存的编辑,提升用户体验
前端·vue.js
多多米10057 小时前
初学Vue(2)
前端·javascript·vue.js
看到请催我学习7 小时前
内存缓存和硬盘缓存
开发语言·前端·javascript·vue.js·缓存·ecmascript
golitter.9 小时前
Vue组件库Element-ui
前端·vue.js·ui
道爷我悟了9 小时前
Vue入门-指令学习-v-on
javascript·vue.js·学习
.生产的驴10 小时前
Electron Vue框架环境搭建 Vue3环境搭建
java·前端·vue.js·spring boot·后端·electron·ecmascript
老齐谈电商10 小时前
Electron桌面应用打包现有的vue项目
javascript·vue.js·electron