vue3如何声明接收props参数的类型
时间: 2023-08-17 18:07:07 浏览: 81
在 Vue 3 中,可以使用 TypeScript 或者 PropTypes 来声明接收 props 参数的类型。
如果你使用 TypeScript,可以通过在组件的 `props` 选项中声明类型来指定 props 的类型。例如:
```typescript
import { defineComponent } from 'vue';
export default defineComponent({
props: {
name: {
type: String,
required: true
},
age: {
type: Number,
default: 18
}
},
setup(props) {
// 使用 props.name 和 props.age
// ...
}
});
```
如果你使用 PropTypes,可以通过在组件中导入 `vue` 和 `vue-property-decorator` 库,并使用装饰器 `@Prop` 来声明 props 的类型。例如:
```typescript
import { Vue, Prop } from 'vue-property-decorator';
import { Component } from 'vue';
@Component
export default class MyComponent extends Vue {
@Prop({ type: String, required: true })
name!: string;
@Prop({ type: Number, default: 18 })
age!: number;
// ...
}
```
无论使用 TypeScript 还是 PropTypes,都可以通过给 props 添加类型和其他属性来定义其类型、是否必需以及默认值等信息。
阅读全文
相关推荐


















