What are Web Components

Web Components in one sentence

Web Components are a suite of different technologies allowing you to create reusable custom elements — with their Functionality Encapsulated away from the rest of your code — and utilize them in your web apps.

In this MDN reference, I have highlighted the key point: reusable custom elements.

Web Components is a set of technologies for creating custom elements that can be reused.

Several concepts

  • Custom Elements: a set of Javascript apis that allow you to create Custom elements and customize their behavior
  • Shadow DOM: a set of Javascript apis that associate the encapsulated “Shadow” DOM tree with specified elements ** **
  • HTML templates: **<template>** and **<slot>** Allows you to write markup templates that are not redisplayed on the page

The basic approach to implementing a Web Component usually looks something like this:

  1. Create a class or function to specify the functionality of a Web component. If you use a class, use the ECMAScript 2015 class syntax.
  2. Using CustomElementRegistry. Define () method to register your new custom element, and transfer to define the elements to its name, specify the element function class, as well as its inherited from optional elements.
  3. Attach a shadow DOM to the custom Element using the element.attachShadow () method, if desired. Add child elements, event listeners, and so on to the Shadow DOM using the usual DOM methods.
  4. Define an HTML template with
  5. Use custom elements wherever you like on the page, just as you would with regular HTML elements.

The above description is mainly from MDN. So how do we write a Toast component based on Web Components?

How to write a Toast component based on Web Components

I started by following the documentation for sample trials and previews. Then think about how I would do that if I were to write a generic third-party Web Compoennts component. So I chose rollup to try it out and publish it to the NPM repository, mainly to compare it to the current mainstream single-page application component writing.

1. Initialize the NPM project

2. Install and configure rollup: For details, see the official rollup website

3, coding implementation

The template structure for the Toast component is defined simply for simplicity

<div><span>This is toast content! </span></div>Copy the code

3.1 Create a class or function to specify the functionality of a Web component

// Create a class or function that specifies the functionality of a Web component. Class Toast extends HTMLElement {constructor() {// super() must be called first; // Call initialization method this.init()} init() {// initialize component related // create shadow root // Create component template this.createTemplate() // Create component style this.createStyle() } } export default Toast;Copy the code

There are two types of Custom Elements:

  • Autonomous Custom Elements are independent elements that do not inherit from other built-in HTML elements. You can write them directly as HTML tags to use on the page. For example, or document.createElement(“webc-toast”).
  • Customized Built-in Elements inherit basic HTML elements. When creating, you must specify the element you want to extend. When using, you need to write out the basic element tag and pass itisProperty specifies the name of the Custom Element. For example,

    , or document.createElement(“p”, {is: “webc-toast”}).

3.2 use CustomElementRegistry. Define () method to register custom elements

customElements.define('webc-toast', Toast);
Copy the code

At this point, we have created a custom component called “webc-toast”.

3.3 Create a shadow root associated with the current component

// create a shadow root. mode specifies whether it can be accessed from outside the element. Return a ShadowRoot object const shadow = this.attachShadow({mode: 'open'});Copy the code

3.4 Creating a Component Template and Adding the corresponding style name

<div><span>This is the Toast content! </span></div> const wrapper = document.createElement('div'); wrapper.setAttribute('class', 'c-toast-wrapper'); const contentWrapper = document.createElement('span'); ContentWrapper. SetAttribute (' class ', 'c - toast - wrapper__cwrapper') / / get the content on the content attribute, Const textContent = this.getAttribute('content'); contentWrapper.textContent = textContent; wrapper.appendChild(contentWrapper); return wrapper; }Copy the code

3.5 Creating component Styles

createStyle() { const show = this.getAttribute('show'); Console.log (show) // Create some CSS and apply it to the shadow DOM const style = document.createElement('style'); style.textContent = ` .c-toast-wrapper { box-sizing: content-box; padding: 5px 20px; text-align: center; position: fixed; left: 50%; transform: translate(-50%, 0); top: 40px; border: solid 1px #eee; border-radius: 10px; user-select: none; color: #0060ff; border-color: #0060ff; background-color: #fff; } `; return style; }Copy the code

3.6 Combine template Styles and add them to Shadow Root

Init () {// create a shadow root const shadow = this.attachShadow({mode: 'open'}); const template = this.createTemplate(); // Create some CSS and apply it to the shadow DOM const style = this.createstyle (); // append the created element to shadow dom shadow.appendChild(style); shadow.appendChild(template); }Copy the code

At this point, we are finished writing the entire component. Making the address

However, we are not using templates and slots yet

4. Life cycle functions

  • connectedCallback: called when the Custom Element is first inserted into the document DOM.
  • disconnectedCallback: called when the Custom Element is removed from the document DOM.
  • adoptedCallback: Called when the Custom Element is moved to a new document.
  • attributeChangedCallback: is called when a custom element is added, removed, or modified.

Problem thinking

  1. How do I develop debug components?
  2. Style precompile support?
  3. Event handling?
  4. How are templates developed and maintained?