简介 Web Components 是一组 web 原生 API 的统称,允许开发者创建可复用的自定义元素 (custom elements)。
我们认为 Vue 和 Web Components 是互补的技术。Vue 为使用和创建自定义元素提供了出色的支持。无论你是将自定义元素集成到现有的 Vue 应用中,还是使用 Vue 来构建和分发自定义元素都很方便。
使用 创建 一个自定义组件 hello.ce.vue 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 <script setup > import { ref } from "vue" ;import { ElButton, ElAlert } from "element-plus" ;defineProps({ msg: String , }); const count = ref(0 );</script > <template > <div class ="box" > <h1 > {{ msg }}</h1 > <img src ="../assets/vue.svg" /> <ElAlert title ="Primary alert" type ="primary" /> <ElAlert title ="Success alert" type ="success" /> <ElAlert title ="Info alert" type ="info" /> <ElAlert title ="Warning alert" type ="warning" /> <ElAlert title ="Error alert" type ="error" /> <div class ="card" > <ElButton type ="primary" round @click ="count++" > count is {{ count }}</ElButton > <p > Edit <code > components/HelloWorld.vue</code > to test HMR </p > </div > <p > Check out <a href ="https://vuejs.org/guide/quick-start.html#local" target ="_blank" > create-vue</a >, the official Vue + Vite starter </p > <p > Learn more about IDE Support for Vue in the <a href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support" target="_blank" >Vue Docs Scaling up Guide</a >. </p > <ElButton class ="read-the-docs" > Click on the Vite and Vue logos to learn more</ElButton > </div > </template > <style > .read-the-docs { color : #888 ; } .box { background-color : #eee ; } .box p { text-decoration : underline; } </style > <style src ="element-plus/dist/index.css" > </style >
提供注册自定义组件函数 webC.js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { defineCustomElement } from 'vue' import MyComponent from './hello.ce.vue' import 'element-plus/dist/index.css' export default function registerComponents ( ) { const MyElement = defineCustomElement({ ...MyComponent, shadowRoot: true }) customElements.define('my-test' , MyElement) }
配置打包 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import path from 'path' const production = { plugins: [ vue({ template: { compilerOptions: { isCustomElement: (tag ) => tag.includes('-' ) } } }) ], build: { lib: { entry: path.resolve(__dirname, 'src/components/webC.js' ), name: 'WebComponentsLibrary' , fileName: (format ) => `web-components.${format} .js` , formats: ['es' , 'umd' ] }, rollupOptions: { external: [], output: { globals: {}, inlineDynamicImports: true } }, cssCodeSplit: false } }; export default defineConfig( production )
安装使用 https://cn.vuejs.org/guide/extras/web-components.html
注意事项 element-ui这种包,css变量会丢失,需要在public/index.html中手动引入变量
es import /export方式引入
umd command script方式
使用vite vue3搭建,vue-cli有诸多问题