网站首页 > 教程文章 正文
方法 1:通过 props 传函数(最直接)
父组件:
<!-- Parent.vue -->
<script setup lang="ts">
import Child from './Child.vue'
function handleClick(msg: string) {
alert(`父组件收到消息:${msg}`)
}
</script>
<template>
<Child :on-click-parent="handleClick" />
</template>
子组件:
<!-- Child.vue -->
<script setup lang="ts">
const props = defineProps<{
onClickParent: (msg: string) => void
}>()
function clickMe() {
props.onClickParent('你好,父组件!')
}
</script>
<template>
<button @click="clickMe">点我调用父组件函数</button>
</template>
优点:简单直接,父组件的方法就是一个普通 prop。
方法 2:子组件通过事件 emit 通知父组件
父组件:
<!-- Parent.vue -->
<script setup lang="ts">
import Child from './Child.vue'
function handleChildEvent(msg: string) {
alert(`父组件收到事件:${msg}`)
}
</script>
<template>
<Child @call-parent="handleChildEvent" />
</template>
子组件:
<!-- Child.vue -->
<script setup lang="ts">
const emit = defineEmits<{
(e: 'call-parent', msg: string): void
}>()
function clickMe() {
emit('call-parent', '来自子组件的消息')
}
</script>
<template>
<button @click="clickMe">点我通知父组件</button>
</template>
优点:更符合 Vue 数据单向流原则,父子解耦。
方法 3:通过 expose() 暴露子组件方法(反向调用)
如果父组件需要直接调用子组件的方法:
<!-- Parent.vue -->
<script setup lang="ts">
import { ref } from 'vue'
import Child from './Child.vue'
const childRef = ref<InstanceType<typeof Child>>()
function callChildMethod() {
childRef.value?.sayHello()
}
</script>
<template>
<Child ref="childRef" />
<button @click="callChildMethod">调用子组件方法</button>
</template>
子组件:
<!-- Child.vue -->
<script setup lang="ts">
function sayHello() {
alert('子组件的方法被调用了!')
}
defineExpose({ sayHello })
</script>
适合父组件主动调用子组件函数,而不是子组件触发父组件。
建议
- 子调父 → 用 事件 emit(方法 2)
- 父调子 → 用 ref + expose(方法 3)
- 直接传函数(方法 1)适合简单场景
猜你喜欢
- 2025-10-13 Vue el-element ui 清空表格选中记录
- 2025-10-13 Vue3基础难点总结_vue3 从入门到实战 进阶式掌握完整知识体系
- 2025-10-13 Vue深入组件:组件事件详解1_组件使用vuex
- 2025-10-13 分享 15 个 Vue3 全家桶开发的避坑经验
- 2025-10-13 vue 3 学习笔记 (八)——provide 和 inject 用法及原理
- 2025-10-13 vue-element-admin 增删改查(五)_vue element admin 登录修改
- 2025-10-13 微信小程序双向数据绑定,父子传参
- 2025-10-13 Vue3 中有哪些值得深究的知识点?_vue常用知识点
- 2025-10-13 Vue3常用的6种组件通信方式,你一定都用过!
- 2025-10-13 面试官:来说说vue3是怎么处理内置的v-for、v-model等指令?
- 最近发表
- 标签列表
-
- location.href (44)
- document.ready (36)
- git checkout -b (34)
- 跃点数 (35)
- 阿里云镜像地址 (33)
- qt qmessagebox (36)
- mybatis plus page (35)
- vue @scroll (38)
- 堆栈区别 (33)
- 什么是容器 (33)
- sha1 md5 (33)
- navicat导出数据 (34)
- 阿里云acp考试 (33)
- 阿里云 nacos (34)
- redhat官网下载镜像 (36)
- srs服务器 (33)
- pico开发者 (33)
- https的端口号 (34)
- vscode更改主题 (35)
- 阿里云资源池 (34)
- os.path.join (33)
- redis aof rdb 区别 (33)
- 302跳转 (33)
- http method (35)
- js array splice (33)