Vite props的几种写法
Vite 组件接受参数的几种写法和区别。
两种方式:
1)运行时声明 2)声明类型
- 可以设置默认值 - 强大的类型推断
- 运行时类型校验 - 编译时类型检查
- ts类型推断较弱 - 不能直接设置默认值
运行时声明:
使用对象语法,用对象定义每个prop的类型、必传、默认值,这里额外提一点对于类型为“对象” 或 “数组” 的默认值需要用函数返回,为什么要用函数返回,是因为如果不适用函数直接设置一个对象会导致所有的实例都会共享同一个对象,当一个实例对象被修改其余实例也会同步修改。
它的特点是运行时校验,在使用组件时如果传错了类型将会在运行时将错误通过throw error出来。
<script setup lang="ts">
const props = defineProps({
age: {
type: Number,
required: true,
default: 1,
},
sex: {
type: Number,
default: 1,
},
name: {
type: String,
default: '',
},
other: {
type: Object,
default: () => ({ time: new Date().getTime() }),
}
})
</script>类型声明:
通常使用泛型方式定义传入,特点是不能直接设置默认值,但Ts类型校验强,在编写时就能提前发现问题,如果需要设置默认值需要借助函数withDefaults。
// 不设置默认值
interface IProps {
age: number;
sex?: number;
name?: string;
other?: {
time: number;
[propsName: string]: unknown;
}
}
const props = defineProps<IProps>();
// 设置默认值
const props = withDefaults(defineProps<IProps>(), {
sex: 1,
name: '',
other: () => ({
time: 0,
})
})
