🎶 Sym - 一款用 Java 实现的现代化社区(论坛/BBS/社交网络/博客)平台

📕 思源笔记 - 一款桌面端笔记应用,支持 Windows、Mac 和 Linux

🎸 Solo - B3log 分布式社区的博客端节点,欢迎加入下一代社区网络

♏ Vditor - 一款浏览器端的 Markdown 编辑器

大前端 - Web Components

2020-02-24

简介

Web Components 是 W3C 正在向 HTML 和 DOM 规范添加的一套功能,他允许在 Web 应用程序中创建可重用的组件。他由以下三部分组成,可单独或组合使用:

  • Custom elements(自定义元素):编写自定义组件的 JavaScript API
  • Shadow DOM(影子 DOM)
  • HTML templates(HTML 模板):包含 <template><slot>

Custom elements

customElements.define(name, customClass, options?) 注册一个 custom element

  • name:元素名称,需使用短横线链接
  • customClass:定义元素交互
  • options:可选参数,用于指定继承的元素。使用时需通过 is 属性指定 name
customElements.define('file-item',
  class extends HTMLElement {
    constructor () {
      super();
  },
)

生命周期

  • connectedCallback:首次插入 DOM 时
  • disconnectedCallback:从 DOM 中删除时
  • adoptedCallback:移动到新的 DOM 中时
  • attributeChangedCallback: 属性被增加、删除、修改时,需先进行属性的监听
    static get observedAttributes () {
        return ['attr']
    }
    

Shadow DOM

Element.attachShadow(options):将定义的元素附加到 DOM 元素上

  • {mode: 'open'} 可以通过 HTMLElement.shadowRoot 获取定义的元素
  • {mode: 'closed'}
const shadowRoot = this.attachShadow({mode: 'open'})
shadowRoot.appendChild(styleElement)
shadowRoot.appendChild(divElement)

HTML templates

<template>:用于保存客户端内容的一种机制。其内容在页面加载时不会呈现,但在运行时可使用 JavaScript 获取。

<table id="producttable">
  <thead>
    <tr>
      <td>UPC_Code</td>
      <td>Product_Name</td>
    </tr>
  </thead>
  <tbody>
    <!-- 现有数据可以可选地包括在这里 -->
  </tbody>
</table>

<template id="productrow">
  <tr>
    <td class="record"></td>
    <td></td>
  </tr>
</template> 
<script>
  // 使用现有的HTML tbody实例化表和该行与模板
  let t = document.querySelector('#productrow'),
  td = t.content.querySelectorAll("td");
  td[0].textContent = "1235646565";
  td[1].textContent = "Stuff";

  // 克隆新行并将其插入表中
  let tb = document.getElementsByTagName("tbody");
  let clone = document.importNode(t.content, true);
  tb[0].appendChild(clone);
  
  // 创建一个新行
  td[0].textContent = "0384928528";
  td[1].textContent = "Acme Kidney Beans";

  // 克隆新行并将其插入表中
  let clone2 = document.importNode(t.content, true);
  tb[0].appendChild(clone2);
</script>

<slot>:Web 组件中的占位符,可使用自己的标记语言进行填充。

<slot name="element-name">NAME</slot> // 声明
<span slot="element-name">slot</span> // 使用时将用 slot 替换 NAME

缺点

  • 仅支持纯 JavaScript 编写
  • 当业务较为复杂时,需自行对其进行数据的传输和绑定

示例

返回总目录

每天 30 秒系列


欢迎注册黑客派社区,开启你的博客之旅。让学习和分享成为一种习惯!

推荐阅读
留下你的脚步