Talk about WEB COMPONENT (Labor Day special update)

origin


Due to the epidemic, the community has been closed for a long time, and the editor is also very busy. I have no time to update technical articles. I will update it during the May Day holiday.
Let’s first talk about why we chose to share this topic. WEB COMPONENT can be regarded as the originator of front-end componentization, earlier than React and Vue. It has always been a series of innovations made by Google to promote technological development, that is, Web Components API . Compared with vue and react, Web Components does not require additional three-party packages, and is faster, lighter, and more direct. If you have experience in vue or react development, this is a quick way to get started. At the same time, Web Components can be compatible with most front-end frameworks, after all, it is based on the browser's native capabilities. There are also some shortcomings. For details, you can Baidu, but the flaws are not hidden. I believe that Web Components will be more perfect in the future.

Overview of Web Components


In fact, there is nothing to say, everyone, go and see the stability, and learn it in minutes. Simply put, it is the following three pieces:

  • Custom elements
  • Shadow DOM
  • HTML templates

Custom elements


We quote the words on the official website:
One of the key features of the Web Components standard is the ability to create custom elements that encapsulate your functionality on an HTML page, rather than having to make do with a long, nested batch of elements that together provide a custom page feature. This article introduces the use of the Custom Elements API.
Do you still not understand after translation? Simply put, it is componentization, defining a component in a standard way, similar to vue and react making wheels.

Shadow DOM


We quote the words on the official website:
An important aspect of web components is encapsulation — being able to keep the markup structure, style, and behavior hidden and separate from other code on the page so that different parts do not clash, and the code can be kept nice and clean. The Shadow DOM API is a key part of this, providing a way to attach a hidden separated DOM to an element. This article covers the basics of using the Shadow DOM.
it can be simply understood as: sandbox, isolation

HTML templates


We quote from the official website:
This article explains how you can use the <template> and <slot> elements to create a flexible template that can then be used to populate the shadow DOM of a web component.
it can be simply understood as: template function, serving Custom elements and Shadow DOM

simple demo


So much has been introduced above, let us apply what we have learned:

class CardTest extends HTMLElement {
  constructor() {
    super();
    let num = 0;
    let container = document.createElement("div");
    container.classList.add("box");
    let button = document.createElement("button");
    button.classList.add("button1");
    button.innerText = "add";
    let span1 = document.createElement("span");
    span1.classList.add("span1");
    span1.innerText = num;
    let span2 = document.createElement("span");
    span2.classList.add("span2");
    span2.innerText = "简单demo:";
    container.append(span2, span1, button);
    this.appendChild(container);
    button.onclick = function () {
      num++;
      span1.innerText = num;
    };
  }
  connectedCallback() {
    console.log("当 custom element首次被插入文档DOM时,被调用");
  }
  disconnectedCallback() {
    console.log("当 custom element从文档DOM中删除时,被调用");
  }
  adoptedCallback() {
    console.log("当 custom element被移动到新的文档时,被调用");
  }
  attributeChangedCallback() {
    console.log("当 custom element增加、删除、修改自身属性时,被调用。");
  }
}

window.customElements.define("card-test", CardTest);

Take a look at the effect:
insert image description here
the picture above shows that the page has just come in.
insert image description here
The picture above shows that after clicking add, you can see that the number has changed from 0 to 1

complex demo


Above code:

class MoreCard extends HTMLElement {
  constructor() {
    super();

    let shadowRoot = this.attachShadow({ mode: "open" });
    let el = document.querySelector("#moreCard").content.cloneNode(true);
    shadowRoot.appendChild(el);

    this.$num = shadowRoot.querySelector("#num");
    this.$button1 = shadowRoot.querySelector("#button1");
    this.$button2 = shadowRoot.querySelector("#button2");
    this.$button1.addEventListener("click", () => {
      this.num++;
    });
    this.$button2.addEventListener("click", () => {
      this.num--;
    });
  }
  get label1() {
    return this.getAttribute("label1");
  }
  set label1(value) {
    this.setAttribute("label1", value);
  }
  get label2() {
    return this.getAttribute("label2");
  }
  set label2(value) {
    this.setAttribute("label2", value);
  }

  get num() {
    return this.getAttribute("num");
  }
  set num(value) {
    this.setAttribute("num", value);
  }

  static get observedAttributes() {
    return ["label1", "label2", "num"];
  }
  attributeChangedCallback(name, oldVal, newVal) {
    console.log("当 custom element增加、删除、修改自身属性时,被调用。");
    this.render();
  }

  render() {
    this.$button1.innerHTML = this.label1;
    this.$button2.innerHTML = this.label2;
    this.$num.innerHTML = `It is ${this.num}`;
  }

  connectedCallback() {
    console.log("当 custom element首次被插入文档DOM时,被调用");
  }
  disconnectedCallback() {
    console.log("当 custom element从文档DOM中删除时,被调用");
  }
  adoptedCallback() {
    console.log("当 custom element被移动到新的文档时,被调用");
  }
}
customElements.define("more-card", MoreCard);

index.html

<template id="moreCard">
      <style>
        span {
          color: red;
          margin-right: 18px;
        }
      </style>
      <span>复杂demo:</span>
      <span id="num"></span>
      <button id="button1"></button>
      <button id="button2"></button>
    </template>
    <more-card num="0" label1="increse" label2="decrease" />

Look at the effect:
insert image description here
insert image description here
insert image description here
the above three pictures represent the components just loaded, click increase, the number will increase by 1, the result is 1, click decrease, the number will decrease by 1, the result is 0

end


The good times are always short-lived, do you have something to gain? After reading this article, do you think it’s just that, it’s so simple, haha, see you in the next issue!

demo address

Guess you like

Origin blog.csdn.net/zjscy666/article/details/124527820