2

Web Components入门实例教程

 1 year ago
source link: https://blog.51cto.com/u_13567403/5358632
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Web Components入门实例教程

原创

彭世瑜 2022-06-05 14:28:51 ©著作权

文章标签 html 代码示例 sed 文章分类 JavaScript 前端开发 阅读数178

<!-- 定义组件模板 -->
<template id="UserNameTemplate">
  <style>
    .user-name {
      color: green;
    }
  </style>
  <div class="user-name"></div>
</template>

<script>
  // 定义组件
  class UserName extends HTMLElement {
    constructor() {
      super();

      let shadow = this.attachShadow({ mode: "closed" });

      let content = document
        .querySelector("#UserNameTemplate")
        .content.cloneNode(true);
      console.log(this.getAttribute("name"));
      content.querySelector(".user-name").innerText =
        this.getAttribute("name");

      shadow.appendChild(content);
    }
  }

  // 注册组件
  window.customElements.define("user-name", UserName);
</script>

<!-- 使用组件 -->
<user-name name="Tom"></user-name>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK