|

Using Custom Elements in Vue.js

Custom Elements are part of the Web Component specification and allow the use of custom HTML tags. After defining them, they are used like any other HTML tag. This means they are agnostic of any Web Frontend Framework. You can use them to bring in some enhanced elements into your page or even compose entire Designsystems with them. Shoelace is a great example of that.

Custom Elements in Vue.js

This sounds great and all, but what if you don't want to learn another new thing? Maybe you already know Vue.js? In this case you might want to take a look at building Custom Elements!

All you need to do is to wrap your vue component in the defineCustomElement() function and register it to the Custom Element registry

customElements.define("hello-vue", defineCustomElement(HelloVue));

By doing this you can leverage (most) of the power of Vue.js. You can also use the SFC approach to build your components. Then you are ready to use your component anywhere you want.

Adding Vue.js to the mix also has some drawbacks. You are not building a "real" Custom Element. It is a Custom Element, but it mounts a Vue instance like any normal Vue.js app would do. This means your Custom Element ships a lot of code. Thus this is not advised to build standalone elements. If you build a component library it's fine, because you can share the library between components.

Another Problem is poor support for Server Side Rendering. There is not a definitive solution to get around this yet. Also scoped Slots are not available for Custom Elements either.

Read more about Vue.js and Custom Elements here:
https://v3.vuejs.org/guide/web-components.html#using-custom-elements-in-vue

And more about Custom Elements here:
https://www.webcomponents.org/introduction