在Vue 3中,父子组件之间的通信可以通过props
和emit
来实现。父组件通过props
向子组件传递数据,子组件通过事件emit
将信息发送回父组件。
父组件 (ParentComponent.vue
):
<template>
<div>
<ChildComponent :parentData="parentData" @childEvent="handleChildEvent" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const parentData = ref('父组件数据');
const handleChildEvent = (value) => {
console.log('子组件触发的事件', value);
};
</script>
子组件 (ChildComponent.vue
):
<template>
<div>
<p>{{ parentData }}</p>
<button @click="sendToParent">发送到父组件</button>
</div>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps(['parentData']);
const emit = defineEmits(['childEvent']);
const sendToParent = () => {
emit('childEvent', '子组件数据');
};
</script>
在这个例子中,父组件通过:parentData="parentData"
将parentData
作为props
传递给子组件,并监听子组件触发的childEvent
事件。子组件通过点击按钮触发sendToParent
函数,该函数通过emit('childEvent', '子组件数据')
发送数据给父组件。