百度外卖网站建设与维护方法,网站建设主题与建设目标,做网站的需要考什么证书吗,小程序推广是干什么的在 vue2 中我们使用选项中的 props 来接受父组件传递过来的数据#xff1b;那在 vue3 的 setup 中#xff0c;我们使用 defineProps 来定义父组件传递过来的数据 1、defineProps 支持的类型有#xff1a;String、Number、Boolean、Object、Array、Function#xff0c;除此之… 在 vue2 中我们使用选项中的 props 来接受父组件传递过来的数据那在 vue3 的 setup 中我们使用 defineProps 来定义父组件传递过来的数据 1、defineProps 支持的类型有String、Number、Boolean、Object、Array、Function除此之外还支持很多高级类型如枚举类型、对象类型、联合类型
2、props 的验证
type: 定义数据的类型
reqiured: 是否必须
default: 默认值
validator: 自定义验证3、使用
3.1在 script setup 中使用
templatediv{{ msg }} - {{ name }} - {{ age }}button click() onClick()点击事件/click/div
templatescript 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])
/script3.2 在 script langts setup 中使用无默认值
templatediv{{ msg }} - {{ name }} - {{ age }}button click() onClick()点击事件/click/div
templatescript langts setup// 采用 ts 声明无默认值interface ChildPropsType {name: stringage: numbermsg: stringonClick: () void
}const props definePropsChildPropsType()
/script3.3 在 script langts setup 中使用有默认值
templatediv{{ msg }} - {{ name }} - {{ age }}button click() onClick()点击事件/click/div
templatescript langts setup// 采用 ts 声明有默认值由于接口不能设置默认值所以要使用 withDefaults 编译宏来实现interface ChildPropsType {name: stringage: numbermsg: stringonClick: () void
}const props withDefaults(definePropsChildPropsType(), {name: bob,age: 17,msg: this is a default msg
})
/script4、注意事项
① defineProps 只能在 setup 中使用且只能在 setup 的顶层使用不能在局部作用域使用
② 和 vue2 一样defineProps 里的属性只读不能修改
③ defineProps 是 vue3 的一个宏函数不需要导入就可以直接使用
④ defineProps 函数返回一个对象是一个 proxy 所有的特性和 reactive 基本相同可以直接在模版上进行使用