What Is a Vue Custom Element?

Vue custom elements are a feature introduced in Vue 3.2. They let you use Vue components or whole applications on non-Vue pages or together with other JavaScript frameworks.
A custom element turns a Vue component into a regular HTML element, so other frameworks or libraries can use it. This makes integrating Vue with other technologies much easier.
To create one, you use the defineCustomElement function. It turns a Vue component into a custom element class, which is then registered with the browser using customElements.define. For example:
import { defineCustomElement } from 'vue';
// Create a Vue component
const MyComponent = defineCustomElement({
template: '<div>Hello, this is my custom element!</div>',
});
// Register it as a custom element
customElements.define('my-component', MyComponent);
// Use it in HTML: <my-component></my-component>
document.body.append(document.createElement('my-component'));Here the MyComponent Vue component is turned into a custom HTML element called "my-component" with defineCustomElement and customElements.define, and it can then be used in any HTML page.
Thanks to this feature, Vue fits into a more modular and flexible architecture that can be combined with other technologies.
Have a question about this article? Write to me


