vue3中的子组件向父组件通信和父组件向子组件通信
一、父组件向子组件通信:Props
父组件通过 属性绑定 传递数据,子组件通过 defineProps
接收数据。
特点:单向数据流(子组件不可直接修改 Props)。
代码示例:
父组件 (ParentComponent.vue):
<template> <ChildComponent :message="parentMessage" :user="userData" />
</template> <script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue'; const parentMessage = ref('Hello from Parent');
const userData = ref({ name: 'Alice', age: 25 });
</script>
子组件 (ChildComponent.vue):
<template> <div> <p>{{ message }}</p> <!-- 输出:Hello from Parent --> <p>{{ user.name }} ({{ user.age }})</p> <!-- 输出:Alice (25) --> </div>
</template> <script setup>
const props = defineProps({ message: { type: String, required: true }, user: { type: Object, default: () => ({}) }
});
</script>
关键点:
Props 需在子组件中显式声明类型和验证规则。
复杂数据(如 Object/Array)应使用
ref
或reactive
保持响应性。
📩 二、子组件向父组件通信:自定义事件
子组件通过 defineEmits
声明事件,用 emit()
触发事件;父组件通过 @事件名
监听并处理数据。
代码示例:
子组件 (ChildComponent.vue):
<template> <button @click="sendData">提交数据</button>
</template> <script setup>
const emit = defineEmits(['data-submitted']); function sendData() { emit('data-submitted', { id: 1, value: '子组件数据' });
}
</script>
父组件 (ParentComponent.vue):
<template> <ChildComponent @data-submitted="handleData" />
</template> <script setup>
function handleData(payload) { console.log(payload); // { id: 1, value: '子组件数据' }
}
</script>