大前端 - Web Components

本贴最后更新于 1523 天前,其中的信息可能已经时移世改

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 秒系列

  • 30Seconds

    📙 前端知识精选集,包含 HTML、CSS、JavaScript、React、Node、安全等方面,每天仅需 30 秒。

    • 精选常见面试题,帮助您准备下一次面试
    • 精选常见交互,帮助您拥有简洁酷炫的站点
    • 精选有用的 React 片段,帮助你获取最佳实践
    • 精选常见代码集,帮助您提高打码效率
    • 整理前端界的最新资讯,邀您一同探索新世界
    488 引用 • 383 回帖 • 5 关注
  • WebComponents

    Web Components 是 W3C 定义的标准,它给了前端开发者扩展浏览器标签的能力,可以方便地定制可复用组件,更好的进行模块化开发,解放了前端开发者的生产力。

    1 引用 • 25 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...