在 vue2 中我们使用选项中的 props 来接受父组件传递过来的数据;那在 vue3 的 setup 中,我们使用 defineProps 来定义父组件传递过来的数据
1、defineProps 支持的类型有:String、Number、Boolean、Object、Array、Function,除此之外还支持很多高级类型,如:枚举类型、对象类型、联合类型
2、props 的验证
type: 定义数据的类型
reqiured: 是否必须
default: 默认值
validator: 自定义验证
3、使用
3.1在 <script setup>
中使用
<template>
<div>
{{ msg }} - {{ name }} - {{ age }}
<button @click="() => onClick()">点击事件</click>
</div>
<template>
<script setup>
// defineProps 返回一个对象,可以定义任意的变量去接收这个对象
// 方式1: 以对象的形式去接收
const props = defineProps({
name: String,
age: {
type: Number,
default: 10,
reqiured: true,
validator: (val) => val > 10
},
msg: {
type: String,
default: () => 'this is a default msg'
},
onClik: Function
})
// props.age = 18 // 报错,注意 defineProps 中的属性只读不能修改
// 方式2: 以数组的方式去接收
const childProps = defineProps(['name', 'age', 'msg', 'onClick'])
</script>
3.2 在 <script lang="ts" setup>
中使用,无默认值
<template>
<div>
{{ msg }} - {{ name }} - {{ age }}
<button @click="() => onClick()">点击事件</click>
</div>
<template>
<script lang="ts" setup>
// 采用 ts 声明无默认值
interface ChildPropsType {
name: string
age: number
msg: string
onClick: () => void
}
const props = defineProps<ChildPropsType>()
</script>
3.3 在 <script lang="ts" setup>
中使用,有默认值
<template>
<div>
{{ msg }} - {{ name }} - {{ age }}
<button @click="() => onClick()">点击事件</click>
</div>
<template>
<script lang="ts" setup>
// 采用 ts 声明有默认值;由于接口不能设置默认值,所以要使用 withDefaults 编译宏来实现
interface ChildPropsType {
name: string
age: number
msg: string
onClick: () => void
}
const props = withDefaults(defineProps<ChildPropsType>(), {
name: 'bob',
age: 17,
msg: 'this is a default msg'
})
</script>
4、注意事项
① defineProps 只能在 setup 中使用,且只能在 setup 的顶层使用,不能在局部作用域使用
② 和 vue2 一样,defineProps 里的属性只读,不能修改
③ defineProps 是 vue3 的一个宏函数,不需要导入就可以直接使用
④ defineProps 函数返回一个对象,是一个 proxy ,所有的特性和 reactive 基本相同,可以直接在模版上进行使用