Vue 3 中 defineProps接收对象类型
时间: 2025-06-09 18:20:02 浏览: 17
### Vue 3 中使用 `defineProps` 接收对象类型的详细说明
在 Vue 3 的组合式 API 中,`defineProps` 是一个编译时宏,用于声明组件的 props。它可以在 `<script setup>` 或普通的 `setup` 函数中使用[^1]。当需要接收对象类型时,可以通过以下方式实现。
#### 使用接口定义对象类型
通过 TypeScript 的接口来定义对象类型的结构,然后将其作为泛型参数传递给 `defineProps`。这种方式可以结合类型检查,确保传入的对象符合预期的结构。
```typescript
<script lang="ts" setup>
interface MyObject {
id: number;
name: string;
details?: { description: string; price: number };
}
const props = defineProps<{
item: MyObject;
}>();
</script>
<template>
<div>
<p>ID: {{ item.id }}</p>
<p>Name: {{ item.name }}</p>
<p v-if="item.details">Description: {{ item.details.description }}</p>
<p v-if="item.details">Price: {{ item.details.price }}</p>
</div>
</template>
```
#### 使用普通对象定义
如果不需要 TypeScript 类型检查,可以直接使用普通对象定义 props 的结构。每个字段可以是一个类型构造函数或包含额外信息的对象[^2]。
```javascript
<script setup>
const props = defineProps({
item: {
type: Object,
required: true,
default: () => ({
id: 0,
name: 'Default Name',
details: { description: 'No description', price: 0 },
}),
},
});
</script>
<template>
<div>
<p>ID: {{ item.id }}</p>
<p>Name: {{ item.name }}</p>
<p v-if="item.details">Description: {{ item.details.description }}</p>
<p v-if="item.details">Price: {{ item.details.price }}</p>
</div>
</template>
```
#### 注意事项
- `defineProps` 返回的 props 对象是一个只读的 proxy 对象,不能直接修改其值[^3]。
- 在模板中可以直接使用 `props` 对象的属性,无需显式解构[^4]。
通过上述方法,可以在 Vue 3 中灵活地使用 `defineProps` 来接收对象类型的 props,并根据需求选择是否结合 TypeScript 进行类型检查。
阅读全文
相关推荐


















