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

如何在Angular应用中复用多个Vue组件?

在Angular中集成多个Vue 2组件的完整方案

一、前置准备

  • 给Angular项目安装依赖:vue@2 和 vue-custom-element,执行命令:
    npm install vue@2 vue-custom-element --save
    
  • 修改app.module.ts,添加CUSTOM_ELEMENTS_SCHEMA让Angular允许自定义HTML标签:
    import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule],
      providers: [],
      bootstrap: [AppComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    export class AppModule { }
    

二、批量注册Vue组件为自定义元素

  1. 创建vue-components-registry.ts文件统一管理组件注册:
    import Vue from 'vue';
    import vueCustomElement from 'vue-custom-element';
    // 导入所有需要集成的Vue组件
    import UserCard from './vue-components/UserCard.vue';
    import DataTable from './vue-components/DataTable.vue';
    import FilterPanel from './vue-components/FilterPanel.vue';
    
    Vue.use(vueCustomElement);
    
    // 批量注册配置
    const componentList = [
      { tagName: 'vue-user-card', component: UserCard, props: ['userId', 'showAvatar'] },
      { tagName: 'vue-data-table', component: DataTable, props: ['tableData', 'pageSize'] },
      { tagName: 'vue-filter-panel', component: FilterPanel, props: ['filterOptions'] }
    ];
    
    componentList.forEach(item => {
      Vue.customElement(item.tagName, item.component, {
        props: item.props // 声明组件需要接收的属性
      });
    });
    
  2. 在main.ts中引入注册文件,确保Angular启动前完成Vue组件注册:
    import './vue-components-registry';
    import { enableProdMode } from '@angular/core';
    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    import { AppModule } from './app/app.module';
    import { environment } from './environments/environment';
    
    if (environment.production) {
      enableProdMode();
    }
    
    platformBrowserDynamic().bootstrapModule(AppModule)
      .catch(err => console.error(err));
    

三、在Angular模板中使用Vue组件

直接在Angular组件的HTML模板中使用自定义标签即可:

<!-- 传入Angular组件中的数据 -->
<vue-user-card [userId]="currentUserId" [showAvatar]="true"></vue-user-card>

<vue-data-table [tableData]="listData" [pageSize]="10" (pageChange)="onPageChange($event)"></vue-data-table>

<vue-filter-panel [filterOptions]="filterConfig"></vue-filter-panel>

四、关键注意事项

  • 属性传递:必须在注册时声明props,否则Angular无法将数据正确传递给Vue组件。
  • 事件监听:Vue组件触发的自定义事件,直接用Angular的()语法监听即可,事件对象会正常传递。
  • 样式处理:Vue组件尽量使用scoped样式避免污染Angular全局样式,若需要调整样式,可在Angular中通过::ng-deep临时处理(不建议过度使用)。
  • 打包优化:组件数量较多时,可通过webpack代码分割实现按需加载,减少初始打包体积。

内容的提问来源于stack exchange,提问作者Charger-Ang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 03:17:07