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

相关推荐
子兮曰4 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰4 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万4 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝4 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
A黄俊辉A4 天前
uniapp webview中实现 app和内嵌的H5双向通信
vue.js·json
三十而立洋4 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁4 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
honkun64 天前
vue 表格组件 vxe-table 配置 ajax 请求自动加载数据与表单查询
vue.js·vxe-table
kybs19914 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
汉堡大王95274 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端