1. 安装 vue-custom-element
npm install vue-custom-element --save
2. 实现WebComponent的vue组件
编写webComponent对应的vue组件,示例代码中只有一个h1标签,
// 文件路径为:@/components/web-component/report/detailed-report.vue
<script lang="js">
</script>
<template>
<div>
<h1>This is from detailed-report</h1>
</div>
</template>
3. 注册自定义的WebComponent
- 在
src/main.js
中执行registerCustomElement()函数注册自定义WebComponent - 实现registerCustomElement()函数
// src.main.js 中的关键代码
// import other package
import registerCustomElement from "@/web-component";
registerCustomElement();
// do something, like : Vue.use(ElementUI)
new Vue({
router, store, render: h => h(App)
}).$mount('#app')
// src/main.js中引入的WebComponent.js代码
import Vue from 'vue'
import vueCustomElement from 'vue-custom-element'
import DetailedReport from '@/components/web-component/report/detailed-report.vue'
export default function registerCustomElement() {
Vue.use(vueCustomElement)
Vue.customElement('custom-detailed-report', DetailedReport)
}
4. 使用自定义的WebComponent
通过以上步骤,已经将custom-detailed-report
标签成功关联到detailed-report.vue
组件,在其他vue中使用<custom-detailed-report/>
即可渲染出vue中的内容。