在 Vue3 中,让父子组件相互执行对方的方法,通常通过以下两种方式实现:
1. 父组件调用子组件的方法
使用 ref 获取子组件实例,子组件通过 defineExpose 暴露方法。
子组件(Child.vue)
<template>
<div>子组件</div>
</template>
<script setup>
import { ref } from 'vue'
const childMethod = () => {
console.log('子组件方法被调用')
}
// 暴露方法给父组件
defineExpose({ childMethod })
</script>父组件(Parent.vue)
<template>
<Child ref="childRef" />
<button @click="callChildMethod">调用子组件方法</button>
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const childRef = ref(null)
const callChildMethod = () => {
childRef.value.childMethod() // 调用子组件暴露的方法
}
</script>2. 子组件调用父组件的方法
通过 emit 触发父组件监听的事件。
父组件(Parent.vue)
<template>
<Child @parent-method="handleParentMethod" />
</template>
<script setup>
const handleParentMethod = (data) => {
console.log('父组件方法被调用', data)
}
</script>子组件(Child.vue)
<template>
<button @click="callParent">调用父组件方法</button>
</template>
<script setup>
const emit = defineEmits(['parent-method'])
const callParent = () => {
emit('parent-method', '来自子组件的数据')
}
</script>补充说明
双向通信:以上两种方式可以同时使用,实现父子互相调用。
Options API:写法类似,
this.$refs获取子组件实例,this.$emit触发事件。跨层级:若需深层嵌套组件通信,可考虑
provide/inject传递方法,或使用全局状态管理(Pinia/Vuex)。