You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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}`)
  }
}

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:01:19