Javascript is required
Mokkapps Logo

Vue Tip: Defining and Registering Vue Web Components

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Nov 4, 2022
1 min read
|
27 views
Template
Script
Defining and Registering Vue Web Components Image

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:

import { defineCustomElement } from 'vue'import Example from './Example.ce.vue'console.log(Example.styles) // ["/* inlined css */"]// convert into custom element constructorconst ExampleElement = defineCustomElement(Example)

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:

customElements.define('my-example', ExampleElement)

3. Use the custom element in your HTML

Finally, we can use our custom element in HTML:

<html>  <body>    <my-example></my-example>  </body></html>

Check out the docs for more details on how this works.


If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.