一篇文章带你简单了解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>
相关推荐
qq8406122334 小时前
Nodejs+vue基于elasticsearch的高校科研期刊信息管理系统_mb8od
前端·vue.js·elasticsearch
程序员林北北9 小时前
【前端进阶之旅】Svelte:编译即框架,让前端开发回归简洁
前端·javascript·vue.js·react.js·html5
pas13611 小时前
46-mini-vue 实现编译 template 为 render 函数
前端·javascript·vue.js
左夕12 小时前
深度解析vue的生命周期
vue.js
随逸17712 小时前
《彻底解决CSS冲突!模块化CSS实战指南》
vue.js·react.js
筱筱°12 小时前
创建一个基于 Vue 的微前端项目
vue.js·微前端
爱看书的小沐15 小时前
【小沐杂货铺】基于Three.js渲染三维无人机Drone(WebGL / vue / react )
javascript·vue.js·react.js·无人机·webgl·three.js·drone
ShenJLLL21 小时前
vue部分知识点.
前端·javascript·vue.js·前端框架
HelloReader1 天前
Tauri 2 创建项目全流程create-tauri-app 一键脚手架 + Tauri CLI 手动接入
前端·javascript·vue.js
哆啦A梦15881 天前
Vue3魔法手册 作者 张天禹 016_vue3中一些特定用法介绍
前端·vue.js·typescript