Vue 3 提供了强大的 Props 系统来实现组件间的数据传递。本文将介绍如何在 Vue 3 中使用 TypeScript 定义和配置 Props。
基础 Props 定义
1. 简单的 Props 定义
TypeScript
// 不带类型的简单定义
const props = defineProps(['name', 'age', 'email'])
2. 带类型的 Props 定义
TypeScript
// 使用对象语法定义类型
const props = defineProps({
name: String,
age: Number,
email: String
})
TypeScript + defineProps
定义 Props 接口
TypeScript
interface Props {
name: string
age?: number // 可选属性
email?: string // 可选属性
isActive: boolean
}
使用 defineProps
TypeScript
const props = defineProps<Props>()
此时未设置默认值的可选属性会是 undefined。
设置默认值:withDefaults
为了给可选属性设置默认值,使用 withDefaults:
TypeScript
interface Props {
name: string
age?: number
email?: string
isActive?: boolean
}
const props = withDefaults(defineProps<Props>(), {
age: 18,
email: '',
isActive: false
})
完整示例
TypeScript
<template>
<div class="user-card">
<h3>{{ props.name }}</h3>
<p>年龄: {{ props.age }}</p>
<p>邮箱: {{ props.email }}</p>
<span :class="{ active: props.isActive }">
{{ props.isActive ? '活跃' : '非活跃' }}
</span>
</div>
</template>
<script setup lang="ts">
interface Props {
name: string
age?: number
email?: string
isActive?: boolean
}
const props = withDefaults(defineProps<Props>(), {
age: 18,
email: 'no-email@example.com',
isActive: false
})
</script>
使用组件
TypeScript
<UserCard
name="张三"
:age="25"
email="zhangsan@example.com"
:is-active="true"
/>
关键要点
- defineProps 是 Vue 3 的编译时宏,无需导入
- withDefaults 用于设置默认值,同样无需导入
- 接口定义 提供完整的 TypeScript 类型支持
- 可选属性 使用
?标记,并可通过withDefaults设置默认值
这套机制让 Vue 3 组件的 Props 系统既类型安全又使用便捷,是现代 Vue 开发的标准做法。