vue3中的子组件向父组件通信和父组件向子组件通信

一、父组件向子组件通信:Props

父组件通过 ​​属性绑定​ ​ 传递数据,子组件通过 defineProps接收数据。

​特点​​:单向数据流(子组件不可直接修改 Props)。

代码示例:

​父组件 (ParentComponent.vue)​​:

java 复制代码
<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)​​:

java 复制代码
<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)应使用 refreactive保持响应性。


📩 二、子组件向父组件通信:自定义事件

子组件通过 defineEmits声明事件,用 emit()触发事件;父组件通过 @事件名监听并处理数据。

代码示例:

​子组件 (ChildComponent.vue)​​:

java 复制代码
<template>  
  <button @click="sendData">提交数据</button>  
</template>  

<script setup>  
const emit = defineEmits(['data-submitted']);  

function sendData() {  
  emit('data-submitted', { id: 1, value: '子组件数据' });  
}  
</script>

​父组件 (ParentComponent.vue)​​:

java 复制代码
<template>  
  <ChildComponent @data-submitted="handleData" />  
</template>  

<script setup>  
function handleData(payload) {  
  console.log(payload); // { id: 1, value: '子组件数据' }  
}  
</script>
相关推荐
码事漫谈2 小时前
当AI开始“思考”:我们是否真的准备好了?
前端·后端
许杰小刀3 小时前
ctfshow-web文件包含(web78-web86)
android·前端·android studio
我是Superman丶3 小时前
Element UI 表格某行突出悬浮效果
前端·javascript·vue.js
恋猫de小郭3 小时前
你的代理归我了:AI 大模型恶意中间人攻击,钱包都被转走了
前端·人工智能·ai编程
xiaokuangren_4 小时前
前端css颜色
前端·css
Huanzhi_Lin4 小时前
关于V8/MajorGC/MinorGC——性能优化
javascript·性能优化·ts·js·v8·新生代·老生代
hoiii1874 小时前
C# 基于 LumiSoft 实现 SIP 客户端方案
前端·c#
anOnion4 小时前
构建无障碍组件之Meter Pattern
前端·html·交互设计
小码哥_常5 小时前
Spring Boot配置diff:解锁配置管理新姿势
前端
小码哥_常5 小时前
告别onActivityResult!Android数据回传的3大痛点与终极解决方案
前端