You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 3中如何定义Props默认值?含Setup脚本场景示例

Vue 3 中 Props 默认值的定义方法

一、基础定义方式

1. 选项式 API

在选项式 API 中,直接在 props 选项里通过 default 字段指定默认值:

<script>
export default {
  props: {
    message: {
      type: String,
      required: true // 必填属性无需设置默认值
    },
    error: {
      type: String,
      default: '' // 为可选属性设置默认值
    }
  }
}
</script>

2. 组合式 API(非 TypeScript 类型声明)

在 <script setup> 中,defineProps 可以接收配置对象,直接配置默认值:

<script setup>
const props = defineProps({
  message: {
    type: String,
    required: true
  },
  error: {
    type: String,
    default: ''
  }
})
</script>

二、TypeScript 类型声明式 Props 的默认值设置

当你通过 TypeScript 接口定义 Props 类型(如示例中的 InputProps),需要使用 Vue 提供的 withDefaults 宏来绑定默认值,它会自动做类型校验,确保默认值符合接口定义:

<script setup lang="ts">
interface InputProps {
  message: string // 必填属性,无需默认值
  error?: string // 可选属性,可设置默认值
}

// 使用 withDefaults 包裹 defineProps,传入默认值配置
const props = withDefaults(defineProps<InputProps>(), {
  error: '' // 为 error 设置默认空字符串
})
</script>

注意事项

  • 必填属性(如示例中的 message)不需要设置默认值,Vue 会强制要求父组件传入该值。
  • withDefaults 的第二个参数必须是对象,键名要和接口中的属性完全匹配,值的类型要符合接口定义的类型。

内容的提问来源于stack exchange,提问作者sadeq shahmoradi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 07:12:05