Javascript is required
·
1 min read
·
477 views

Vue Tip: Defining and Registering Vue Web Components

Vue Tip: 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:

1import { defineCustomElement } from 'vue'
2import Example from './Example.ce.vue'
3
4console.log(Example.styles) // ["/* inlined css */"]
5
6// convert into custom element constructor
7const 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:

1<html>
2  <body>
3    <my-example></my-example>
4  </body>
5</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:

I will never share any of your personal data. You can unsubscribe at any time.