发布于 

Vue3 setup defineProps使用

使用宏在Vue3中定义和使用技巧

使用场景

当想要在组件中使用 props 时,需要在 script setup中使用 defineProps 宏来声明 props 的类型和选项。defineProps 是一个编译时的宏,它会被转换成相应的 runtime props 选项,并且返回一个包含了 props 值的对象,可以直接在 script setup 中使用这个对象来访问 props

使用方法

有两种方式可以使用 defineProps 宏来声明 props:

基于类型的声明

可以直接给 defineProps 传递一个泛型参数,表示 props 的类型。这个泛型参数必须是一个对象字面量类型或者是一个同文件内定义的接口类型。例如:

1
2
3
4
5
6
7
8
<script setup lang="ts">
interface Props {
value?: string
id: number
}

const props = defineProps<Props>()
</script>

这样,就可以在 script setup 中使用 props.value 和 props.id 来访问 props 的值,并且享受 TypeScript 的类型推断和检查

基于运行时的声明

也可以给 defineProps 传递一个对象字面量,表示 props 的运行时选项,例如 type、required、default 等。例如:

1
2
3
4
5
6
7
8
9
<script setup lang="ts">
const props = defineProps({
foo: {
type: String,
required: true
},
bar: Number
})
</script>

这样,也可以在 script setup 中使用 props.foo 和 props.bar 来访问 props 的值,并且享受 TypeScript 的类型推断和检查。但是,这种方式有一些限制,比如不能使用导入的类型作为泛型参数,也不能声明默认值

使用拓展

当使用基于类型的声明时,可能会遇到一个问题:如何给 props 设置默认值?这时,可以使用 withDefaults 编译时宏来解决。withDefaults 接受两个参数:第一个是 defineProps 返回的对象,第二个是一个包含了默认值的对象。例如:

1
2
3
4
5
6
7
8
9
10
11
<script setup lang="ts">
interface Props {
msg?: string
labels?: string[]
}

const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two']
})
</script>

这样,就可以给 msg 和 labels 设置默认值,并且享受 TypeScript 的类型检查和推断。另外,withDefaults 还会自动移除那些有默认值的属性的可选标记,这样就不需要在使用它们时加上非空断言

相关参考