第4章 组件通信

组件通信这话题,说实话我讲了这么多年,每次都能碰到新问题。Vue 的组件通信方式多样,但很多同学在用 TypeScript 的时候反而迷了路——不知道该在哪定义类型,更不知道 emit 还能做校验。这一节,咱们就把它彻底聊透。

4.1 用类型把 props 锁死

咱们先看看最基础的 props 定义。Vue 3 + TypeScript 下,我强烈建议用 defineProps 配合泛型来写。这比单纯用 String、Number 这种运行时声明要靠谱得多。

<script setup lang="ts">
// 方式一:类型声明(推荐)
interface UserInfo {
  id: number
  name: string
  avatar?: string
  role: 'admin' | 'user' | 'guest'
}

const props = defineProps<{
  user: UserInfo
  isActive?: boolean
  tags: string[]
}>()

// 方式二:带默认值(使用 withDefaults)
withDefaults(defineProps<{
  user: UserInfo
  count?: number
>(), {
  count: 0
})
</script>

为什么我更推荐类型声明?因为它在编译阶段就能帮你发现错误。我遇到过好几次,用运行时声明写了 type: [String, Number],结果传参的时候传了个布尔值进去,页面直接渲染不出来。用 TypeScript 类型,这种低级错误根本不会发生。

实战技巧:如果你需要同时使用 props 和 emit,建议把它们的类型定义都放在 <script setup lang="ts"> 外部的 interface 或 type 中,这样组件外部引用类型时也会方便一些。

4.2 emit:不只是声明,还得"管"住它

emit 的类型校验,说白了就是告诉 TypeScript:我这个组件能发哪些事件,每个事件带什么参数。我个人习惯直接把事件名和参数类型定义在一起:

<script setup lang="ts">
// 定义事件的结构
interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'delete-item', id: number): void
  (e: 'save-success', payload: { code: number; message: string }): void
}

const emit = defineEmits<Emits>()

// 使用时类型安全
const handleDelete = (id: number) => {
  emit('delete-item', id) // ✅ 正确
  // emit('delete-item', 'abc') // ❌ 类型报错
}

const handleSave = () => {
  emit('save-success', { code: 200, message: 'ok' }) // ✅
}
</script>

有一次我接手了一个老项目,里面的组件 this.$emit('change') 到处乱飞,根本没人知道哪个事件要传什么参数。后来我花了整整一天把所有的 emit 都定义成接口,才勉强梳理清楚。

4.3 父组件如何接收类型安全的 emit

子组件定义了严格的 emit,父组件那侧也必须配套跟上。Vue 3.3 之后有个很舒服的写法,可以直接这样用:

<!-- ChildComponent.vue -->
<script setup lang="ts">
interface ItemPayload {
  id: number
  name: string
}

const emit = defineEmits<{
  (e: 'item-click', payload: ItemPayload): void
  (e: 'item-remove', id: number): void
}>()
</script>

<!-- ParentComponent.vue -->
<script setup lang="ts">
interface ItemPayload {
  id: number
  name: string
}

const handleClick = (payload: ItemPayload) => {
  console.log(payload.name)
}

const handleRemove = (id: number) => {
  // 这里的参数类型被自动推断为 number
}
</script>

<template>
  <ChildComponent 
    @item-click="handleClick" 
    @item-remove="handleRemove"
  />
</template>

你可能会问,父组件怎么知道 @item-click 携带什么参数?答案是:TypeScript 会从子组件的 defineEmits 类型中自动推导。这其实省了不少事——只要子组件写对,父组件那边基本不会踩坑。

4.4 provide / inject:跨层级的类型安全

provide / inject 在大型项目中用得越来越多。但它的类型安全确实容易翻车。我在项目中见过最常见的坑是:provide 的时候没写类型,inject 的时候随便断言了个类型,结果运行到一半发现数据不是预想的样子。

// 用 InjectionKey 来保证类型一致
import { provide, inject, type InjectionKey } from 'vue'

// 定义 key(单独放到 types.ts 文件里更好)
export const UserInfoKey: InjectionKey<{
  name: string
  age: number
  updateName: (name: string) => void
}> = Symbol('user-info')

// 在祖先组件中提供
const userStore = reactive({
  name: '张三',
  age: 28,
  updateName(name: string) {
    this.name = name
  }
})

provide(UserInfoKey, userStore)

// 在后代组件中注入
const userInfo = inject(UserInfoKey)
if (!userInfo) {
  throw new Error('UserInfoKey 未提供')
}

console.log(userInfo.name) // 类型安全 ✅
注意:inject 有可能会返回 undefined,尤其是当你不确定祖先组件是否 provide 了对应值时。所以每次 inject 之后,我都习惯先做一次存在性判断,或者给默认值。别怕麻烦,这一步能省不少调试时间。

4.5 用 readonly 保护 props 不被改

Vue 本身就不推荐子组件改 props,但运行时不会报错。加上 TypeScript 后,我们可以直接 readonly 一把梭:

interface Props {
  readonly config: { theme: string; size: number }
  readonly list: string[]
}

const props = defineProps<Props>()

// 编译阶段就会报错
// props.config.theme = 'dark'  // ❌ Cannot assign to 'theme' 

嗯,说白了这就是一种编程纪律。我以前遇到过一个同事,子组件里偷偷改了 props 里的对象属性,导致父组件的数据也变了,整个页面状态全乱了。用类型约束一下,这种问题从源头就能堵住。

4.6 完整的类型安全通信示例

最后我放一个整合的示例,把前面讲的内容全串起来。这也是我在实际项目中比较喜欢的写法。

<!-- types.ts -->
export interface Product {
  id: number
  title: string
  price: number
}

export interface CartActionPayload {
  product: Product
  quantity: number
}

export const CartKey: InjectionKey<{
  items: Product[]
  addItem: (product: Product) => void
  removeItem: (id: number) => void
}> = Symbol('cart-store')

<!-- CartProvider.vue -->
<script setup lang="ts">
import { reactive, provide } from 'vue'
import { CartKey, type Product } from './types'

const items = reactive<Product[]>([])

const addItem = (product: Product) => {
  items.push(product)
}

const removeItem = (id: number) => {
  const index = items.findIndex(item => item.id === id)
  if (index !== -1) items.splice(index, 1)
}

provide(CartKey, { items, addItem, removeItem })
</script>

<!-- ProductCard.vue -->
<script setup lang="ts">
import { inject } from 'vue'
import { CartKey, type Product } from './types'

const props = defineProps<{
  product: Product
}>()

const emit = defineEmits<{
  (e: 'add-to-cart', payload: { product: Product; quantity: number }): void
}>()

const cartStore = inject(CartKey)

const handleAdd = () => {
  emit('add-to-cart', { product: props.product, quantity: 1 })
  cartStore?.addItem(props.product)
}
</script>

大家可以对比一下,如果没有 TypeScript,这些代码里的类型信息全丢了,组件之间的契约关系就只能靠文档和自觉来维护。哪天真出了线上问题,排查起来真的很费劲。

核心总结:props 用类型定义来锁数据,emit 用接口约束来管事件,provide/inject 用 InjectionKey 来保证跨层级的类型一致性。这几招用好了,组件的健壮性和可维护性直接上一个台阶。我自己在多个中型项目里实践过,至少能减少 30% 的通信相关 bug。
组件通信类型安全 Props 定义 defineProps<> withDefaults 默认值 类型别名 / Interface 可选属性 ? readonly 保护 编译期校验 父传子 Emit 事件 defineEmits<{}> 事件名 + 参数类型 父组件类型推导 @event 自动提示 Payload 接口复用 多事件声明 子传父 Provide / Inject InjectionKey<T> Symbol() 唯一标识 provide 值类型绑定 inject 自动推断 undefined 保护判断 跨层级共享状态 祖先 → 任意后代
小建议:如果你在团队里维护一个组件库,我建议把这些类型定义都抽到 types.ts 文件里集中管理。组件内部引用导入,外部使用者也方便查看,而且不容易出现类型不同步的问题。