How to use Web Components in Vue for beginners

How to use Web Components in Vue for beginners

VueJS is a new JavaScript framework that has recently gained a lot of popularity for its simple API and easier learning curve. In this article, I will show you how to use and interact with web components in Vue application. We will build a small user interface to add people to the data grid.

We are using the Vue CLI to generate a new project.

$ vue create webcomponents
$ cd webcomponents
Install components

The first step in using web components is installing them. In this case, we install vaadin-text-field, vaadin-button, and vaadin-grid from the Vaadin component set.

$ npm install --save @vaadin/vaadin-text-field @vaadin/vaadin-button @vaadin/vaadin-grid

Add polyfills for older browsers
Although most modern browsers ship with built-in support for Web Components, there are still users out there with older browsers. If you want to make your app available to them as well, you want to include polyfills that emulate the functionality in browsers without native support.

The webcomponents.js polyfill comes with a loader script that can be used to load only the polyfills a particular browser needs. It loads the polyfills dynamically so it cannot be imported directly as a JS dependency that gets built by Webpack. Instead, you need to copy over the dependencies and include the loader in your index file. The library also contains an ES5 compatibility script for apps that have been transpiled into ES5.

$ npm install --save-dev copy-webpack-plugin @webcomponents/webcomponentsjs

Copy polyfills

The first thing we need to do is copy over the polyfills. You can do this by providing Vue with an additional Webpack configuration. Create a new file, vue.config.js in the root of your project.

vue.config.js

const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  configureWebpack: {
    plugins: [
      new CopyWebpackPlugin([
        {
          context: 'node_modules/@webcomponents/webcomponentsjs',
          from: '**/*.js',
          to: 'webcomponents'
        }
      ])
    ]
  }
};

The CopyWebpackPlugin will now copy over all the needed JavaScript files into a webcomponents directory in the dist directory when building.

Load polyfills

Then, include the loader and an optional import for the ES5 compatibility script in the <head> section of index.html.

public/index.html

<script src="webcomponents/webcomponents-loader.js"></script>
<script>
  if (!window.customElements) { document.write('<!--'); }
</script>
<script src="webcomponents/custom-elements-es5-adapter.js"></script>
<!-- ! DO NOT REMOVE THIS COMMENT, WE NEED ITS CLOSING MARKER -->

Verify that you can run the application with

$ npm run serve

Building the application

You are now ready to use web components. Begin by importing the components in the <script> section your HelloWorld.vue component.

src/components/HelloWorld.vue

import '@vaadin/vaadin-button';
import '@vaadin/vaadin-grid';
import '@vaadin/vaadin-text-field';

The form and grid bind to a Person object with firstName and lastName properties. Create a class definition for it. You can add it directly underneath the imports.

src/components/HelloWorld.vue

class Person {
  constructor() {
    this.firstName = "";
    this.lastName = "";
  }
}

Finally, replace the component implementation with the following:

src/components/HelloWorld.vue

export default {
  name: "HelloWorld",
  data: function() {
    return { 
      people: [],
      currentPerson: new Person()
    };
  },
  methods: {
    addPerson: function() { 
      this.people = [...this.people, this.currentPerson];
      this.currentPerson = new Person();
    }
  }
};
  1. The data model consists of an array of people along with the person currently being edited.

  2. The addPerson method creates a new array including the edited person and assigns it to people and finally resets the current person.

Defining the view HTML

With the logic in place, you can now define the view using the web components in the <template> section of HelloWorld.vue.

src/components/HelloWorld.vue

<div class="component">
    <div class="form" @keyup.enter="addPerson">
      <vaadin-text-field
        label="First Name"
        :value="currentPerson.firstName"
        @input="currentPerson.firstName = $event.target.value"
      ></vaadin-text-field>
      <vaadin-text-field
        label="Last Name"
        :value="currentPerson.lastName"
        @input="currentPerson.lastName = $event.target.value"
      ></vaadin-text-field>
      <vaadin-button @click="addPerson">Add</vaadin-button>
    </div>
    <vaadin-grid :items.prop="people"> 
      <vaadin-grid-column path="firstName" header="First name"></vaadin-grid-column>
      <vaadin-grid-column path="lastName" header="Last name"></vaadin-grid-column>
    </vaadin-grid>
  </div>

Notice that you need to bind the people array with :items.prop in order to assign the JS array as a property. Otherwise Vue attempts to serialize the array and set it as an attribute.

Vue handles v-model binding differently for components than native <input> elements. To get the binding to work, we need to bind and update the value ourselves with :value="currentPerson.firstName" @input="currentPerson.firstName = $event.target.value". This is exactly how v-model works under the hood.

Finally, update the CSS to make the form look nicer:

src/components/HelloWorld.vue

.form {
  margin-bottom: 16px;
}
.form * {
  margin-right: 4px;
}

If you want to match the look of the screenshot in the beginning, update App.vue as well:

src/App.vue

<template>
  <div id="app">
-    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>
---
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
-  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

If you run the application now with npm run serve, you should have a working application using web components.

Conclusion

Once you have installed polyfills for older browsers, you can use Web Components interchangeably with Vue components. For the most part, you would use Web Components as leaf node components, and Vue for views and other composite components.

Learn More

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.