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 开发的标准做法。

相关推荐
前端不太难1 天前
从 Navigation State 反推架构腐化
前端·架构·react
前端程序猿之路1 天前
Next.js 入门指南 - 从 Vue 角度的理解
前端·vue.js·语言模型·ai编程·入门·next.js·deepseek
大布布将军1 天前
⚡️ 深入数据之海:SQL 基础与 ORM 的应用
前端·数据库·经验分享·sql·程序人生·面试·改行学it
川贝枇杷膏cbppg1 天前
Redis 的 RDB 持久化
前端·redis·bootstrap
D_C_tyu1 天前
Vue3 + Element Plus | el-table 表格获取排序后的数据
javascript·vue.js·elementui
JIngJaneIL1 天前
基于java+ vue农产投入线上管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
天外天-亮1 天前
v-if、v-show、display: none、visibility: hidden区别
前端·javascript·html
jump_jump1 天前
手写一个 Askama 模板压缩工具
前端·性能优化·rust
hellotutu1 天前
vue2 从 sessionStorage 手动取 token 后,手动加入到 header
vue.js·token·session·header
be or not to be1 天前
HTML入门系列:从图片到表单,再到音视频的完整实践
前端·html·音视频