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

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

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

http://www.xdnf.cn/news/2065.html

相关文章:

  • 一洽 全力辅助商户平台在线咨询解决方案
  • 自定义异常处理(全局异常处理)
  • Vue多地址代理端口调用
  • Promethues 普罗米修斯
  • 小刚说C语言刷题——1565成绩(score)
  • 某地农产品交易中心钢网架自动化监测项目
  • 筛法求莫比乌斯函数
  • 4月25日星期五今日早报简报微语报早读
  • ZYNQ-GPIO之MIO中断
  • 【计算机视觉】CV实战项目 - 深入解析基于HOG+SVM的行人检测系统:Pedestrian Detection
  • 管家婆财贸ERP BB103.收款单按明细核算部门项目
  • Java真的不难(五十五)Stream流的进阶用法
  • 题解:CF2106G2 Baudelaire (hard version)
  • html+servlet项目中的echart图表
  • 期刊论文发表,对重复率和AI率要求多少才合格?
  • 【MySQL数据库入门到精通-07 函数-字符串函数、数值函数、日期函数和流程函数】
  • 微差压传感器、呼吸传感器
  • C++开发未来发展与就业前景:从底层基石到未来引擎
  • 无限debugger实现原理
  • 皖维 大病救助办理手续说明
  • 分层设计数据仓库的架构和设计高效数据库系统的方法
  • 大模型应用开发之LLM入门
  • AI大模型学习十二:‌尝鲜ubuntu 25.04 桌面版私有化sealos cloud + devbox+minio对象存储测试和漫长修改之路
  • apt 源切到国内时出现证书验证不过问题
  • 异步请求池控制同一时间并发
  • [官方IP] AXI Memory Init IP
  • GAEA情感坐标背后的技术原理
  • HashMap的源码解析
  • Gradle安装与配置国内镜像源指南
  • Jira、PingCode、Redmine等18款缺陷管理工具对比评测