Integrating Web Components in Vue

Vue is another one of those libraries that is growing incredibly fast, so I thought it would be a good thing if we saw how a web component can be included in a Vue component.

Let's say we have a <main-body> Vue component that looks something like this:

Vue.component('main-body', {
props: ['src', 'alt'],
template: `
<p>This is the main body</p>
`,
})

As you can see, it does nothing other than show text, just like the main body component in Angular and React. Let's say we want to include the <header-image> web component to this <main-body> component. This would make the <main-body> component look something like this:

import HeaderImage from '../web-components/header-image/header-image.js';

Vue.component('main-body', {
props: ['src', 'alt'],
template: `
<p>This is the main body</p>
<header-image src="{{src}}" alttext="{{alt}}"></header-image>
`,
created: function() {
customElements.define('header-image', HeaderImage);
}
})

Here, we are simply importing the HeaderImage component and registering the web component inside the created() callback method. As you can see, it is very simple to use a web component inside a Vue component, and the attribute values can be passed into the web component via interpolation, as shown in the previous code.

Using the process stated in this section, we can add an already-existing web component to any Vue project. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.179.186