angular中混用vue的解决方案

使用vue2

关键技术点:

web component

vue component

参考文档

https://blog.enginaar.com/vue-angular-together-in-one-app/

使用vue3

注意:

  • 现行vue3版本不支持 web component (vue3 2.x)
  • vue的相关特性如事件、双向绑定等特性无法使用vue组件时直接用,需要相关处理放在vue组件内部完成

直接引入文件方式

  1. 在angular 项目中找到 index.html 文件,将需要引入的vue 组件的js和css 引入
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <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>

  1. 在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')

  }

}

npm 方式

注: 现有项目 typescript 和 vue3 、Vant 的typescript 有冲突,升级有点复杂