angular混入vue,注册组件解决方案

301 阅读1分钟

blog.enginaar.com/vue-angular…

vue2 方式

参考文档: cli.vuejs.org/zh/guide/bu…

vue3 方式

  • vue@3.2.x 暂时不支持构建 Web Components,所以通过构建库模式打包组件库
  • vue的相关特性如时间、双向绑定等无法使用vue组件时直接使用,需要相关处理放在vue组件内部完成
  • Web Component 方式打包报错
Vue 3 support of the web component target is still under development.

直接引入文件方式

1、在 angular 项目中找到 index.html 文件,将需要引入的 vue组件库的 js 和 css 引入

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>测试</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <!-- import style -->
  <link
    rel="stylesheet"
    href="https://fastly.jsdelivr.net/npm/vant@3/lib/index.css"
  />

  <!-- import script -->
  <script src="//unpkg.com/vue@next"></script>
  <script src="https://fastly.jsdelivr.net/npm/vant@3/lib/vant.min.js"></script>
</head>
<body >
  <app-root ></app-root>
</body>
</html>

2、在 angular 项目中 @NgModule 指定 schemas:[CUSTOM_ELEMENTS_SCHEMA]

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  schemas:[CUSTOM_ELEMENTS_SCHEMA],
 declarations:[]
 })
 

3、使用 vue 组件 html 文件

<div class="homeImgDiv" >
  <img src="../../../assets/default/progress.png">
  <div id="defaultCp">
    <van-button type="primary">Primary</van-button>
    <van-password-input style="width: 250px" v-bind:value="value"
                        v-bind:show="showKeyboard"
                        v-bind:focused="showKeyboard"
                        v-on:focus="onblur"></van-password-input>
    <van-number-keyboard
      v-bind:value="value"
      v-bind:show="showKeyboard"
    ></van-number-keyboard>
  </div>

</div>

ts文件


// 添加 Vue 的声明
declare var Vue: any;

export class DefaultComponent implements OnInit {

  constructor() {
  }

  ngOnInit(): void {
    
    // 关键代码
    Vue.createApp({
    }).use(vueComponent) // 注册 vue 组件
      .mount('#defaultCp')

  }

}