Vue3 组件通信本质:Props 下发,Emits 回传

张开发
2026/4/18 12:10:19 15 分钟阅读

分享文章

Vue3 组件通信本质:Props 下发,Emits 回传
辅助理解 Props Emits官网原文地址Props互动教程https://cn.vuejs.org/tutorial/#step-12Emits互动教程https://cn.vuejs.org/tutorial/#step-13如下代码的大致流程子组件点击按钮 ↓ emit(increment, i) ↓ 父组件 increment 接收 ↓ handleIncrement(val) ↓ 父组件执行逻辑App.vuescript setup import { ref } from vue import ChildComp from ./ChildComp.vue const greeting ref(Hello from parent) const handleIncrement (val) { console.log(子组件传回来的值:, val) } /script template !-- 父组件可以使用 v-on 简写 监听子组件触发的事件 -- ChildComp :msggreeting incrementhandleIncrement/ /templateChildComp.vuescript setup // 声明触发的事件 const emit defineEmits([increment]) // defineProps() 是一个编译时宏并不需要导入 const props defineProps({ msg: String }) let i 0 const increment123 () { // 带参数触发 emit(increment, i) } /script template h2{{ msg || No props passed yet }}/h2 button clickincrement123子组件点我/button /template 关键理解非常重要❌ 错误思维子组件去“改父组件逻辑”✅ 正确思维子组件只负责“发信号”最终你要形成的“脑内模型”数据在父组件ref ↓ props 传给子组件 ↓ 子组件不能改 props ↓ 只能 emit 通知父组件改 ↓ 父组件更新 → props 再下发仅供学习参考

更多文章