By Dennis Burger, Poort80 Amsterdam, september 2018
This is a little demo that uses VueJS's vue-cli
v3.x to build a W3C Web-Component from a Vue component. This custom Web-component, with a custom made up HTML-tag, can then be dropped into a (non-Vue) web page. Or any other web page that uses any framework.
- NodeJS
- You'll also need the
vue-cli
. After installing above NodeJS open a Terminal (command-line) and run:
npm i -g @vue/cli
This will install the VueJS vue-cli command-line-interface (CLI).
Run the usual NPM install from within this project directory to install it's dependencies.
npm install
For this demo we'll focus on the src/components/NameBlock.vue
-page. And it into a custom W3C HTML-tag with a JavaScript file. Run the following to start the local (hot-reloading) development web server.
npm run serve
Open the src/components/NameBlock.vue
-page (component) into a text-editor (or IDE). This VueJS component (page) will be turned into a W3C Web-component.
When done developing; quit the running development server by hitting ctrl + c
on the terminal. Now run the command below to have vue-cli
v3.x build this component into a W3C web-component inside the docs/
directory. To change this docs/
directory edit the vue.config.js
and update the package.json
-file demo
-script (to serve which directory).
I've used the docs/
directory because this project is hosted on Github and this demo can be viewed from the Github Pages on a custom domain .
npm run build
The result is a very short static docs/demo.html
-page. With a few HTML <script>
-tags.
<script src="https://unpkg.com/vue"></script>
<script src="./name-block.js"></script>
<name-block></name-block>
- The first
<script>
-line is the VueJS library loaded from a CDN. - The second
<script>
-line is theHome.vue
application all wrapped up into one JavaScript file. - The third is that custom HTML-tag name you'll use for your VueJS Web-component.
To quickly view (or 'serve') this docs/
directory run the command below. This will start a simple HTTP web server serving the docs/
directory.
npm run demo
Open the URL mentioned in the terminal in a web browser. The docs/index.html
file contains a demo of a normal HTML page where the <name-block></name-block>
W3C web-component is used.
Now you can use this custom HTML-tag <name-block></name-block>
along with those two <script>
-tags inside other web pages.
This setup uses the Shadow DOM for self-contained components.
As of this writing this VueJS Web-component demo works in:
- Chrome
- Firefox
- Safari
- Opera
- Edge (with polly-fill)