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.value
  emit('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: string
  age: number
}

const props = defineProps<{
  user: User
  theme?: string  // 可选属性
}>()

四、最佳实践建议

  1. 命名规范

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

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

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

结语

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

  • 父传子defineProps
  • 子传父defineEmits

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值