一篇文章带你简单了解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>
相关推荐
起名时在学Aiifox1 小时前
从零实现前端数据格式化工具:以船员经验数据展示为例
前端·vue.js·typescript·es6
放牛的小伙2 小时前
vue 表格 vxe-table 加载数据的几种方式,更新数据的用法
vue.js
pas1362 小时前
25-mini-vue fragment & Text
前端·javascript·vue.js
满天星辰2 小时前
Vue 响应式原理深度解析
前端·vue.js
满天星辰3 小时前
Vue真的是单向数据流?
前端·vue.js
boooooooom3 小时前
深入浅出 Vue3 defineModel:极简实现组件双向绑定
vue.js
pas1363 小时前
29-mini-vue element搭建更新
前端·javascript·vue.js
裴嘉靖4 小时前
Vue + Element UI 实现复选框删除线
javascript·vue.js·ui
pas1364 小时前
19-mini-vue setup $el $data $props
javascript·vue.js·ecmascript
xkxnq5 小时前
第一阶段:Vue 基础入门(第 10 天)
前端·javascript·vue.js