我有一个在Vue中构建的项目,我想在Angular应用程序中重用Vue应用程序中的组件,因此我不必从头开始重建每个组件。
我在How to use Vue 2.0 components in an angular application上看到了本教程,但该教程是针对AngularJS的。
我想知道是否有人以前这样做过,是否值得,是否有人知道任何教程或参考资料。
将Vue组件包装为native Web Components。
由于Angular支持使用自定义Web组件,因此您可以使用Vue组件(包装为Web组件)。
对于Angular,无论自定义Web组件是否由Vue生成(对于所有Angular知道,它们都可能是原生HTML元素,都没有关系。
该演示是Angular 5应用。 Vue自定义组件在index.html
中定义。注意如何在index.html
中将其直接用作模板,就好像它是本机元素一样。
下面逐步操作。
使用app/app.component.html
将Vue组件包装为Web组件:
app/app.component.html
将创建一个可直接在DOM中使用的vue-custom-element
Web组件,无需要一个有效的Vue实例。
以上只是可直接在浏览器中运行的演示。如果您有。vue文件和一个vue-cli应用程序,则需要执行vue-custom-element
,然后创建一个<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/[email protected]/dist/vue-custom-element.js"></script>
<script>
const MyVueWebComp = {
props: ['msg'],
template:`
<div style="border: 3px dashed green; padding: 5px">
I am my-vue-web-comp.<br>
Value of "msg" prop: {{ msg }}<br>
<input v-model="text"><button @click="addText">Click me</button>
<div v-for="t in texts">
Text: {{ t }}
</div>
</div>
`,
data() {
return {
text: '',
texts: []
};
},
methods: {
addText() {
this.texts.push(this.text);
this.text = '';
}
}
};
Vue.customElement('my-vue-web-comp', MyVueWebComp);
</script>
文件,例如:
<my-vue-web-comp>
然后捆绑在一起时,将生成一个npm install vue-custom-element --save
文件,可以直接将其作为单个.js
标签导入,代替上面的整个代码和脚本标签。
有关更多详细信息,请检查import Vue from 'vue';
import vueCustomElement from 'vue-custom-element';
import MyElement from './MyElement.vue';
Vue.use(vueCustomElement);
Vue.customElement('my-element', MyElement);
。
现在,在Angular应用中,导入Web组件(是否由Vue生成)后,通过在.js
中添加<script>
来vue-custom-element
's docs:
vue-custom-element
现在直接在Angular模板中使用Web组件(是否由Vue生成)。例如。上面代码中定义的组件可以像这样使用:
configure them to be used by Angular
实际上是可运行的演示schemas: [CUSTOM_ELEMENTS_SCHEMA]
您可能需要使用polyfill才能获得较旧的浏览器支持。请检查@NgModule
了解更多详细信息。