Vue 3 Props 定义详解:从基础到进阶

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" 
/>

关键要点

  1. defineProps 是 Vue 3 的编译时宏,无需导入
  2. withDefaults 用于设置默认值,同样无需导入
  3. 接口定义 提供完整的 TypeScript 类型支持
  4. 可选属性 使用 ? 标记,并可通过 withDefaults 设置默认值

这套机制让 Vue 3 组件的 Props 系统既类型安全又使用便捷,是现代 Vue 开发的标准做法。

相关推荐
崔庆才丨静觅2 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60612 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了3 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅3 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅3 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅3 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment3 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅4 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊4 小时前
jwt介绍
前端
爱敲代码的小鱼4 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax