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

Vue3中如何获取组件类型以在TypeScript接口中使用

Vue组件的TypeScript类型定义方案

根据你使用的Vue版本,分别对应以下类型定义方式:

Vue 3 场景

Vue 3 中所有组件的通用类型是 Component,可以直接从vue包导入,用来约束任意Vue组件:

import type { Component } from 'vue';

// 定义包含组件的接口
interface DynamicComponentItem {
  component: Component; // 约束为任意Vue组件
  key: string; // 动态切换时的唯一标识,可选但推荐添加
  // 可根据需求添加其他属性,比如标题、描述等
}

// 组件数组示例
const dynamicComponents: DynamicComponentItem[] = [
  { component: UserProfile, key: 'profile' },
  { component: SettingsPage, key: 'settings' }
];

使用<script setup>语法编写的组件也完全兼容Component类型,无需额外处理。

Vue 2 场景

Vue 2 中组件的通用类型是 VueConstructor,从vue包导入即可:

import type { VueConstructor } from 'vue';

interface DynamicComponentItem {
  component: VueConstructor;
  key: string;
}

const dynamicComponents: DynamicComponentItem[] = [
  { component: HomePage, key: 'home' },
  { component: AboutPage, key: 'about' }
];

这样就能确保数组中的component字段只能传入合法的Vue组件,完全满足你动态组件切换的类型校验需求。

内容的提问来源于stack exchange,提问作者Samuel M. Bednarz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 02:33:29