在Vue 3中,子组件调用父组件的方法通常是通过触发自定义事件来实现的。父组件监听这些事件,然后执行相应的处理逻辑。下面是一种典型的实现方式:
//父组件:
<template>
<ChildComponent @child-event="parentMethod" />
</template>
<script setup>
import ChildComponent from './ChildComponent.vue';
function parentMethod(dataFromChild) {
console.log('父组件接收到的数据:', dataFromChild);
// 这里可以是父组件的任何业务逻辑
}
</script>
//子组件
<template>
<button @click="sendToParent">点击发送数据给父组件</button>
</template>
<script setup>
import { defineEmits } from 'vue';
const emits = defineEmits(['child-event']);
const sendToParent = () => {
emits('child-event', '这是来自子组件的数据');
};
</script>