一篇文章带你简单了解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>
相关推荐
i220818 Faiz Ul29 分钟前
动漫商城|基于springboot + vue动漫商城系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·动漫商城系统
摸鱼仙人~3 小时前
增量快照 vs 结构化共享:适用场景全解析
前端·vue.js
A923A4 小时前
【小兔鲜电商前台 | 项目笔记】第八天
前端·vue.js·笔记·项目·小兔鲜
清风絮柳6 小时前
65.少儿英语微信小程序
vue.js·spring boot·微信小程序·小程序·毕业设计
摸鱼仙人~10 小时前
Vue中markdown-it基础使用教程
前端·javascript·vue.js
落魄江湖行10 小时前
入门篇二:Nuxt 4路由自动生成:告别手动配置路由的日子
前端·vue.js·typescript·nuxt4
xiaotao13111 小时前
第八章:实战项目案例
前端·vue.js·vite·前端打包
源码站~13 小时前
基于Spring Boot+Vue3的烹饪交流学习系统 设计与实现
java·vue.js·spring boot·后端·mysql·毕业设计·毕设
小小小米粒13 小时前
原生 JS:数据和视图「分离」,必须手动同步原生 JS 里,数据是数据,视图是视图,两者完全没关系
前端·javascript·vue.js