当前位置: 首页 > news >正文

vue3父子组件传值

父 → 子:props

父组件

<template><ChildComponent :message="parentMessage" :user="user" />
</template><script setup>
import ChildComponent from './ChildComponent.vue';
const parentMessage = 'Hello from parent';
const user = { name: 'Alice', age: 25 };
</script>

子组件

<template><p>{{ message }}</p><p>{{ user.name }} - {{ user.age }}</p>
</template><script setup>
// 声明 props
const props = defineProps({message: {type: String,required: true},user: {type: Object,required: true}
});
</script>

子 → 父:emit 事件

<template><button @click="sendToParent">Send to Parent</button>
</template><script setup>
const emit = defineEmits(['send-data']);function sendToParent() {emit('send-data', 'Data from child');
}
</script>

父组件

<template><ChildComponent @send-data="handleChildData" />
</template><script setup>
import ChildComponent from './ChildComponent.vue';function handleChildData(data) {console.log('Received:', data); // 输出 "Received: Data from child"
}
</script>

相关文章:

  • Linux系统编程---Signal信号集
  • Datawhale PyPOTS时间序列5月第1次笔记
  • 【速写】TRL:Trainer的细节与思考(PPO/DPO+LoRA可行性)
  • JavaWeb 开发的核心基础知识
  • 2025-05-13 学习记录--Python-条件判断:if语句 + if-else语句 + if-elif-else语句 + match语句
  • 码蹄集——分解、数组最大公约数、孪生质数、卡罗尔数、阶乘数
  • The Deep Learning Compiler: A Comprehensive Survey (深度学习编译器:全面调查)
  • py7zr解压文件时报错CrcError(crc32, f.crc32, f.filename)
  • Kubernetes 入门笔记
  • 磁盘存储链式的 B 树与 B+ 树
  • 数据库原理实验:视图与索引
  • Python训练打卡Day23
  • Biba安全模型详解:守护信息系统完整性的基石
  • 网络安全-等级保护(等保) 2-3 GB/T 22240—2020《信息安全技术 网络安全等级保护定级指南》-2020-04-28发布【现行】
  • JAVA:synchronized总结
  • 大模型核心运行机制
  • C语言中的宏
  • Prometheus参数配置最佳实践
  • P1032 [NOIP 2002 提高组] 字串变换
  • shell脚本变量详解
  • 国务院关税税则委员会关于调整对原产于美国的进口商品加征关税措施的公告
  • 俄土外长通话讨论俄乌谈判问题
  • 老人将房产遗赠给外孙,三个女儿却认为遗嘱应无效,法院判了
  • 巫蛊:文化的历史暗流
  • 普京提议恢复直接谈判,泽连斯基:望俄明日停火,乌愿谈判
  • 一生要出片的年轻人,买爆相机