云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

Vue 3 子组件调用父组件函数的主要三种方式

jxf315 2025-10-13 23:12:31 教程文章 1 ℃

方法 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)适合简单场景
最近发表
标签列表