Vue是否具备React中ElementType类似的类型?
Vue中类似React ElementType的类型方案
Vue没有内置和React ElementType完全对应的类型,但可以通过组合Vue提供的已有类型,实现相同的组件/HTML标签传递能力。
核心类型组合
在Vue 3 + TypeScript中,常用的类型组合如下:
import type { Component } from 'vue' // 对应React ElementType,支持HTML标签名、Vue组件 type VueElementType = string | Component
string:对应HTML原生标签(如'div'、'span')Component:对应Vue组件(包括defineComponent定义的组件、组件选项对象)
实际使用示例
1. 定义接受组件/标签的Props
import { defineComponent, PropType } from 'vue' import type { Component } from 'vue' const MyWrapper = defineComponent({ props: { // 允许传入HTML标签名或Vue组件 as: { type: [String, Object] as PropType<string | Component>, default: 'div' } }, setup(props) { return () => h(props.as, { class: 'wrapper' }, 'Wrapped content') } })
2. JSX/TSX中使用
如果用Vue的TSX语法,写法和React高度相似:
import { defineComponent } from 'vue' import CustomCard from './CustomCard.vue' const DynamicComponent = defineComponent({ props: { component: { type: [String, Object] as PropType<string | Component>, required: true } }, render() { const TargetComponent = this.component return <TargetComponent title="Hello Vue">Card content</TargetComponent> } }) // 调用示例 <DynamicComponent component="section" /> <DynamicComponent component={CustomCard} />
3. 类型安全的组件Props传递
如果需要让传入的props和目标组件的类型匹配,可以结合ComponentProps工具类型:
import type { Component, ComponentProps } from 'vue' type DynamicComponentProps<C extends Component> = { component: C componentProps?: ComponentProps<C> } const DynamicComponent = defineComponent(<C extends Component>(props: DynamicComponentProps<C>) => { return () => h(props.component, props.componentProps) })
总结
Vue虽然没有内置ElementType,但通过string | Component的联合类型,完全可以实现React中传递组件/标签的场景,结合Vue的类型工具还能保证类型安全性。
内容的提问来源于stack exchange,提问作者djkloop
相关产品推荐
相关产品推荐

