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>
相关推荐
哈__4 分钟前
React Native 鸿蒙跨平台开发:StatusBar 状态栏组件
javascript·react native·react.js
C_心欲无痕20 分钟前
nginx - 核心概念
运维·前端·nginx
开开心心_Every24 分钟前
安卓做菜APP:家常菜谱详细步骤无广简洁
服务器·前端·python·学习·edge·django·powerpoint
前端_Danny26 分钟前
用 ECharts markLine 实现节假日标注
前端·信息可视化·echarts
古城小栈28 分钟前
Rust 丰富&好用的 格式化语法
前端·算法·rust
丢,捞仔38 分钟前
uni-app上架应用添加权限提示框
前端·javascript·uni-app
Glink44 分钟前
从零开始编写自己的AI账单Agent
前端·agent·ai编程
Hilaku44 分钟前
我是如何用一行 JS 代码,让你的浏览器内存瞬间崩溃的?
前端·javascript·node.js
努力犯错玩AI44 分钟前
如何在ComfyUI中使用Qwen-Image-Layered GGUF:完整安装和使用指南
前端·人工智能
Lefan1 小时前
在浏览器中运行大模型:基于 WebGPU 的本地 LLM 应用深度解析
前端