Vue3中setup函数传入的props参数类型是什么?
Vue3 setup函数中props参数的类型处理
自动类型推导(推荐方案)
Vue3会基于你在props选项中的配置,自动为setup函数的props参数推导准确的类型,无需手动额外声明。
注意你代码里的一处错误:type: Object as PropType<String>写法不合理——如果是字符串类型,直接用String作为type即可;只有处理自定义对象、数组这类复杂类型时,才需要用PropType来指定具体类型。
修正后的示例代码:
import { h, ref, PropType } from 'vue' // 声明自定义类型示例(如果需要) interface Brand { name: string logo: string } export default { props: { // 简单字符串类型,直接用原生构造函数 msg: { type: String, required: true }, // 复杂对象类型,用PropType指定具体接口 brand: { type: Object as PropType<Brand>, required: true } }, setup(props) { // 此时props会自动被推断为:{ msg: string; brand: Brand } const count = ref(0) return () => h('div', `${props.msg} ${count.value}`) } }
手动显式声明类型(可选)
如果需要明确指定props的类型,可以先定义Props接口,再在setup函数中为props参数指定该类型:
import { h, ref, PropType } from 'vue' interface Props { msg: string brand: { name: string logo: string } } export default { props: { msg: { type: String, required: true }, brand: { type: Object as PropType<Props['brand']>, required: true } }, setup(props: Props) { // 显式指定props为Props类型 const count = ref(0) return () => h('div', `${props.msg} ${count.value}`) } }
相关产品推荐
相关产品推荐

