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

Vue 3 父子组件通信案例详解:Props 与 Emits 实战

前言

在 Vue 3 开发中,组件通信是最基础也是最重要的技能之一。本文将用实际案例演示 Vue 3 中最常用的两种父子通信方式:Props(父传子)和 Emits(子传父),帮助大家快速掌握 Composition API 下的组件通信技巧。


一、Props 父传子实战

场景描述

我们有一个父组件 ParentComp 需要向子组件 ChildComp 传递用户信息和主题颜色。

代码实现

<!-- 父组件 ParentComp.vue -->
<template><div class="parent"><ChildComp :user="userData" :theme="themeColor"@theme-change="handleThemeChange"/></div>
</template><script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'const userData = ref({name: '张三',age: 25,avatar: 'https://example.com/avatar.jpg'
})const themeColor = ref('blue')function handleThemeChange(newColor) {themeColor.value = newColor
}
</script>
<!-- 子组件 ChildComp.vue -->
<template><div :class="`user-card ${theme}`"><img :src="user.avatar" alt="头像"><h3>{{ user.name }}</h3><p>年龄: {{ user.age }}</p><button @click="changeTheme">切换主题</button></div>
</template><script setup>
// 定义 props 接收父组件数据
const props = defineProps({user: {type: Object,required: true},theme: {type: String,default: 'light' // 默认值}
})// 定义 emits
const emit = defineEmits(['theme-change'])function changeTheme() {const newTheme = props.theme === 'blue' ? 'green' : 'blue'emit('theme-change', newTheme) // 触发事件
}
</script><style scoped>
.user-card.blue {border: 2px solid blue;
}
.user-card.green {border: 2px solid green;
}
</style>

关键点解析

  1. defineProps:子组件通过此方法声明接收的 props

    • 可以指定类型、必填性和默认值
    • 支持复杂对象类型校验
  2. props 使用:通过 props.xxx 访问父组件传递的值

    • 模板中可直接使用
    • script 中需要通过 props 对象访问

二、Emits 子传父实战

场景描述

子组件需要通知父组件用户点击了"喜欢"按钮,并传递商品ID和喜欢状态。

代码实现

<!-- 父组件 ParentComp.vue -->
<template><div><ProductItem v-for="product in products" :key="product.id":product="product"@like="handleLike"/></div>
</template><script setup>
import { ref } from 'vue'
import ProductItem from './ProductItem.vue'const products = ref([{ id: 1, name: 'Vue 3教程', price: 99 },{ id: 2, name: 'TypeScript手册', price: 88 }
])function handleLike({ id, isLiked }) {const product = products.value.find(p => p.id === id)console.log(`${product.name} ${isLiked ? '已点赞' : '取消点赞'}`)
}
</script>
<!-- 子组件 ProductItem.vue -->
<template><div class="product"><h4>{{ product.name }}</h4><p>价格: {{ product.price }}元</p><button @click="toggleLike">{{ isLiked ? '取消喜欢' : '喜欢' }}</button></div>
</template><script setup>
import { ref } from 'vue'const props = defineProps({product: Object
})// 定义 emits 并添加验证
const emit = defineEmits({like: ({ id, isLiked }) => {if(id && typeof isLiked === 'boolean') {return true}console.warn('无效的 like 事件参数')return false}
})const isLiked = ref(false)function toggleLike() {isLiked.value = !isLiked.valueemit('like', {id: props.product.id,isLiked: isLiked.value})
}
</script>

关键点解析

  1. defineEmits:子组件通过此方法声明要触发的事件

    • 可以添加事件参数验证
    • 支持 TypeScript 类型定义
  2. emit 触发:通过 emit('事件名', 参数) 通知父组件

    • 可以传递任意类型参数
    • 推荐使用对象形式传递多个参数

三、常见问题解答

Q1: 为什么我的 props 修改无效?

A: Vue 遵循单向数据流原则,子组件不能直接修改 props。如果需要"修改",应该通过 emit 事件让父组件修改。

Q2: defineProps 和 defineEmits 需要导入吗?

A: 不需要!它们是 <script setup> 中的编译器宏,会自动编译为正确的选项。

Q3: 如何在 TypeScript 中定义 props 类型?

interface User {name: stringage: number
}const props = defineProps<{user: Usertheme?: string  // 可选属性
}>()

四、最佳实践建议

  1. 命名规范

    • props 使用 camelCase 定义,模板中使用 kebab-case
    • 自定义事件名使用 kebab-case
  2. 复杂数据

    • 对象类型的 props 建议使用接口定义
    • 考虑使用 toRefs 解构 props 保持响应性
  3. 性能优化

    • 避免在 props 中传递大型对象
    • 不变的 props 可以使用 v-once

结语

通过本文的两个实战案例,相信你已经掌握了 Vue 3 中最核心的父子组件通信方式。记住:

  • 父传子defineProps
  • 子传父defineEmits

在实际开发中,合理运用这些通信方式可以让你的组件更加清晰可维护。如果有任何问题,欢迎在评论区留言讨论!

相关文章:

  • MySQL 详解之用户、权限与审计:保障数据安全的基石
  • MCP协议:AI与工具无缝连接的“万能插头“及最佳实践指南
  • MySQL 详解之函数:数据处理与计算的利器
  • SQLMesh 表格对比指南:深入理解 table_diff 工具的实际应用
  • 每日两道leetcode(补充一)
  • 【FreeRTOS】事件标志组
  • 58、微服务保姆教程(一)
  • 第十一天 主菜单/设置界面 过场动画(Timeline) 成就系统(Steam/本地) 多语言支持
  • HTML 模板技术与服务端渲染
  • 2022李宏毅老师机器学习课程笔记
  • 【尚硅谷Redis6】自用学习笔记
  • 【C++游戏引擎开发】第25篇:方差阴影贴图(VSM,Variance Shadow Maps)
  • 使用Python脚本在Mac上彻底清除Chrome浏览历史:开发实战与隐私保护指南
  • chrome://inspect/#devices 调试 HTTP/1.1 404 Not Found 如何解决
  • 伊克罗德信息亮相亚马逊云科技合作伙伴峰会,以ECRobot 智能云迁移助手在GenAI Tech Game比赛勇夺金牌!
  • 【文献阅读】建立高可信度的阴性样本,改进化合物-蛋白质相互作用预测
  • CSS常遇到自适应高度动画、带三角气泡阴影一行样式解决
  • 论文阅读:2024 NeurIPS Group Robust Preference Optimization in Reward-free RLHF
  • Jenkins Pipeline 构建 CI/CD 流程
  • Promethues 普罗米修斯
  • 刘非任中共浙江省委常委、杭州市委书记
  • 神舟二十号载人飞船发射升空
  • 韩国检方起诉前总统文在寅
  • 北朝时期的甲胄
  • 特朗普:无意解雇鲍威尔,但美联储应该降低利率
  • 广汽全域赋能,领程皮卡概念车重磅登陆上海车展