父组件调用子组件的方法

父组件

在父组件中调用子组件的sayHello()函数

javascript 复制代码
<template>
	<div>
		<button @click="getChild('wendu')">触发子组件方法wendu</button>
		<button @click="getChild('shidu')">触发子组件方法shidu</button>
		<el-dialog v-model="dialogVisible" title="title" width="80%" draggable style="background: #091b37 !important; padding:1px !important" :close-on-click-modal="false">
			<transition>
				<keep-alive>
					<component :is="Child" ref="childRef" :key="b"> </component>
				</keep-alive>
			</transition>
		</el-dialog>
	</div>
</template>
<script setup>
import { ref, nextTick } from 'vue'
import Child from './components/wendu.vue'

const b = ref('')
const dialogVisible = ref(false)
// 定义与 ref 同名变量
const childRef = ref(null)
const getChild = (a) => {
  dialogVisible.value = true
  b.value = a
  nextTick(() => {
    if (childRef.value) {
      console.log(childRef.value);
      console.log(childRef.value.sayHello);
      childRef.value.sayHello(a);
    } else {
      console.log("子组件尚未渲染");
    }
  })
}
</script>

子组件

javascript 复制代码
<template>
	<div>我是子组件</div>
	<input type="text" v-model="inputValue">
</template>
 
<script setup>
import { ref, defineExpose } from 'vue'

// 第一步:定义子组件的方法
const sayHello = (value) => {
	console.log(value)
}
// 第二部:暴露方法
defineExpose({
	sayHello 
})
</script>
相关推荐
ss2736 分钟前
SpringBoot+vue养老院运营管理系统
vue.js·spring boot·后端
渔_6 分钟前
uni-app 图片预览 + 长按保存,超实用!
前端
八哥程序员7 分钟前
从DOM结构到布局流:display: content的深度解析与实战应用
前端·css
Shaneyxs7 分钟前
从 0 到 1 实现CloudBase云开发 + 低代码全栈开发活动管理小程序(07)
前端
Shaneyxs9 分钟前
从 0 到 1 实现CloudBase云开发 + 低代码全栈开发活动管理小程序(10)
前端
Shaneyxs10 分钟前
从 0 到 1 实现CloudBase云开发 + 低代码全栈开发活动管理小程序(05)
前端
用户8417948145611 分钟前
vue 甘特图 vxe-gantt table 依赖线的使用,配置连接线
vue.js
Shaneyxs13 分钟前
从 0 到 1 实现CloudBase云开发 + 低代码全栈开发活动管理小程序(08)
前端
掘金一周16 分钟前
【用户行为监控】别只做工具人了!手把手带你写一个前端埋点统计 SDK | 掘金一周 12.18
前端·人工智能·后端