With Vue CLI 3 building Web Components never was easier.
Everything we need is one .vue
(Single File Component) file.
Install Vue CLI 3 if You don’t have it yet.
npm install -g @vue/cli
and additional global addon to have access to instant prototyping
npm install -g @vue/cli-service-global
Now we can create our simple Vue component.
<template> <div> Hello <strong>{{ name || 'Stranger' }}</strong>! </div> </template> <script> export default { props: ['name'] } </script> <style scoped> strong { color: fuchsia; } </style>
And Build it as web component
vue build --target wc --name wc-hello hello.vue
Our Web Component is ready, now we can use it on our page.
Note that Vue needs to be available as a global variable as it is not packed inside component. This is not to duplicate code when we have dozens or hundreds of components.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue.js Web Component</title> <script src="https://unpkg.com/vue"></script> <script src=" dist/wc-hello.js"></script> </head> <body> <wc-hello name="rad"></wc-hello> </body> </html>
It’s working!
Read more:
Web Components Introduction
Vue CLI 3: Instant Prototyping
Vue CLI 3: Build Targets
@vue/web-component-wrapper