关于vue.js:如何在angular中使用vue

2次阅读

共计 2014 个字符,预计需要花费 6 分钟才能阅读完成。

将 Vue 组件包装为本 Web 组件。

因为 Angular 反对应用自定义 Web 组件,因而可能应用 Vue 组件(包装为 Web 组件)。

对于 Angular,如果自定义 Web 组件是由 Vue 生成的,那么它就没有区别(对于所有 Angular 都晓得,它们能够是本机 HTML 元素)

咱们应用 vue-custom-element 来来进行包装

demo 地址:这里应用 element-ui 作为组件导入 angular 应用
代码地址

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-custom-element@3.0.0/dist/vue-custom-element.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
  const MyVueWebComp = {props: ['msg'],
    template:`
    <div style="border: 3px dashed green; padding: 5px">
      I am my-vue-web-comp.<br>
      Value received via "msg" prop: {{msg}}<br>
      <input v-model="text"><button @click="addText">Type something and click me</button>
      <div v-for="t in texts">
        Text: {{t}}
      </div>
      <div>
            <el-button @click="show()"  type="danger">Button</el-button>
        <el-dialog :visible.sync="visible" title="Hello world">
            <p> 我是 vue Element 组件 </p>
        </el-dialog>
      </div>
  
    </div>
    `,
    data() {
      return {
        text: '',
        texts: [],
        visible : false

      };
    },
    methods: {addText() {this.texts.push(this.text);
        this.text = '';
      },
        show() {this.visible = true;}
    }
  };
  Vue.customElement('my-vue-web-comp', MyVueWebComp);
</script>

<my-app>loading</my-app>

如果是 ts 内应用(同样 vue.js 也是再 index.html 引入)

declare var Vue: any;
  • app.module.ts

当初,在 angular 里,导入 Web 组件后,其配置为应用退出 schemas: [CUSTOM_ELEMENTS_SCHEMA]:

import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';

import {AppComponent} from './app.component';

@NgModule({imports:      [ BrowserModule, FormsModule],
  declarations: [AppComponent],
  bootstrap:    [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA // Added for custom elements support]
})
export class AppModule {}
  • app.component.html

当初间接在 Angular 模板中应用 Web 组件(从 Vue 生成或不生成)。例如,下面代码中定义的组件能够像以下一样应用:

<h3>Hello, {{name}}</h3>

<p>In index.html, a Vue component is defined using Vue and is wrapped into a Web Component using vue-custom-element.<br>

Now, in Angular's template, use it as if it were a native HTML Element (or regular native Web Component).
</p>

<my-vue-web-comp [msg]="name"></my-vue-web-comp>

无关更多详细信息,请查看 vue-custom-element 文档。
参考

正文完
 0