Vue Custom Elements (3 Part Series)
One of the niceties that the CLI will give you is the ability to compile your Vue components into custom HTML tags. I've talked about how to get this set up in What are custom HTML elements and in Building custom elements from Vue CLI. This article is about how to then compile and export those components so that they are ready to put on any web page.
The process of turning Vue into an official, browser supported Web Component is handled via a Vue build tool called
@vue/web-component-wrapper. This will take your component and build it into the format needed by the Web Component standard. This transpiling from a Vue component to a custom component is already built into Vue CLI, so if your project was created with Vue CLI, all you have to do to export a component to a custom component is this:
vue-cli-service build --target wc --name my-blink 'src/components/Blink.vue'
This will create three files in your
||The code for your component minus the Vue library|
||A simple demo HTML file for your component|
||The debugging information for your browser|
||The minified version of the component|
||The debugging information for the minified version|
The important thing to know here is that you must include the Vue library in your HTML wherever you want to use your component. It's not included in the build itself. If you look at the demo HTML file that was created during the build process, you'll see that in action.
<script src="https://unpkg.com/vue"></script> <script src="./my-blink.js"></script> <my-blink></my-blink>
You can then use that
demo.html file to test out the component.
What if you have multiple components that you want to turn into Web Components? You don't need to build each one individually, you can instead build them all at once.
vue-cli-service build --target wc-async --name demo 'src/components/*.vue'
This will build your components into multiple files that are actually lazy loaded into the browser. If you don't use a certain component, its file won't be loaded in. Nice!
But what about the
--name? When you defined that in your single component build, it made the tag that name. But here you have multiple components. What does it do now?
--name is used as a prefix for your tags. So if your Vue component is named
blink and the
--name is defined as
demo, then your tag will export as
Now you can build your Vue components, take the
js files from
dist and drop them onto any web page. Then just include the tag anywhere in your HTML and BOOM Vue components on any page.