Web Components is an umbrella term for a set of web native APIs that allows developers to create reusable custom elements. Vue has excellent support for both consuming and creating custom elements.
Info
The main advantage of web components is that they can be used with any framework or even without a framework.
In three simple steps, let's look at how we can create a web component from a Vue SFC (single-file component).
1. Create the custom element
To create the custom element, we use defineCustomElement
:
You may have noticed that our SFC uses the special file ending .ce.vue
. It inlines the SFC's <style>
tags as strings of CSS and exposes them under the component's styles option.
During production build with default tooling setup, the <style>
inside the SFCs are extracted and merged into a single CSS file. But for the custom component, the <style>
tags should be injected into the custom element's shadow root.
2. Register the custom element with the DOM
Next, we can register the custom element using the define
method. After registration, all <my-example>
tags on the page will be upgraded afterward:
3. Use the custom element in your HTML
Finally, we can use our custom element in HTML:
Check out the docs for more details on how this works.
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Share Composable State Across Components
It is possible to sync composable state across components by lifting its definition outside the exported function.
Vue Tip: Use Vue Without Build Step
When using Vue from a CDN, no "build step" is involved. This makes the setup much more straightforward and is suitable for enhancing static HTML or integrating with a backend framework.