Vue in Custom Element

As a part of Sloth project I came across the need to embed Vue into a page as a widget. As it has been more of a struggle than expected this post needed to be written.

First step to do in making Vue embeddable is to change build target. The default build target created by Vue CLI is meant to be deployed as an SPA. In order to build widget enclosed by a custom element we need to add target flag:

wc   is an abbreviation for Web Component.

As the next step we need to decide whether Vue should be inlined or not. Inlining means that Vue is included in final JavaScript file. This is useful when we plan to have only one Vue widget on the page because only one file will have to be linked. On the other hand inline flag isn’t useful on a page with several widgets.

In case we choose to inline, we’ll add flag:

As the last thing with the tooling we need to add name of the tag:

When it’s all put together, build  target in package.json  looks like:

The main change in the code is that main.ts or JavaScript equivalent is no longer the entry file for our application. The role of entry file is assigned to the first component, usually App.vue . So when we need to use tools like Vuex we have to import them there instead of in the main file. So TypeScript part of my App.vue  looks like this:

Now we are ready to build and deploy things. As you can see we have there a prop token  which we can use on the page as an attribute:

To be able to work with props during development we need to edit main.ts because serve target wasn’t changed. The default render function contains only App argument, so to pass props we need to add second argument, object containing token prop.

Now we are ready to make widgets in Vue.js.

Note: As this widget uses Custom Elements, please, be aware that it won’t work in IE11.

Resources

https://cli.vuejs.org/guide/build-targets.html#web-component

https://itnext.io/vuidget-how-to-create-an-embeddable-vue-js-widget-with-vue-custom-element-674bdcb96b97

https://github.com/karol-f/vue-custom-element

https://caniuse.com/#search=Custom%20Elements