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

相关推荐
0思必得020 分钟前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice22 分钟前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶36023 分钟前
php怎么实现订单接口状态轮询(二)
前端·php·接口
大橙子额1 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
LYFlied2 小时前
从 Vue 到 React,再到 React Native:资深前端开发者的平滑过渡指南
vue.js·react native·react.js
爱喝白开水a3 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌413 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
B站_计算机毕业设计之家3 小时前
豆瓣电影数据采集分析推荐系统 | Python Vue Flask框架 LSTM Echarts多技术融合开发 毕业设计源码 计算机
vue.js·python·机器学习·flask·echarts·lstm·推荐算法
吃杠碰小鸡4 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone4 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word