学习Web Components
博客文章
A Complete Introduction to Web Components in 2022
- 视频讲解:https://www.youtube.com/watch?v=hVxZ-te0kio
-
What Are Web Components?
-
A Brief History of Web Components
- 首发:2011 https://fronteers.nl/congres/2011/sessions/web-components-and-model-driven-views-alex-russell
- 首现:2016 https://github.com/Polymer/polymer
- Firefox 2018, Edge in 2020
- 预制件
- 需要HTML5知识:https://kinsta.com/blog/html-vs-html5/
-
Getting Started With Web Components
- 由从HTMLElement派生的ES2015标类作成
- Firefox允许HTMLParagraphElement,HTMLImageElement以及HTMLButtonElement
- 使用CustomElementRegistry 注册
- 例如:
customElements.define( 'hello-world', HelloWorld );
- 例如:
- 组件须提供
- connectedCallback()
- 等等
-
Adding Attributes
- 对应到标类的成员
- 对应attributeChangedCallback()回调
-
Lifecycle Methods
- constructor()
- 等等
- 由从HTMLElement派生的ES2015标类作成
-
How Web Components Interact With Other Elements
-
The Shadow DOM
- 用于隔离外部JS或CSS的影响,有open和closed两种模式
- 比如:
const shadow = this.attachShadow({ mode: 'closed' });
-
HTML Templates
- 可以通过
<template>
来定义模板,可以被web组件标类克隆- 比如:
const template = document.getElementById('hello-world').content.cloneNode(true);
- 比如:
- 可以直接修改克隆之后的DOM,修改之后才添加到Shadow DOM中
- 可以通过
-
Template Slots
- 留槽位,供插入的操作,应该很熟悉了
- 有默认的槽位
- 只能用.assignedNodes()来访问槽位集合
- 虽可以给槽位指定样式,但对于插入到槽位的元素无法直接指定其样式
- 槽位的插入不依赖于Javascript
-
The Declarative Shadow DOM
- Chrome上的试作:experimental declarative Shadow DOM
-
Shadow DOM Events
- 可以侦听Shadow DOM上的事件
- 内部传播上来的事件会变成是从ShadowDOM根上发出的
-
-
Using Web Components in Other Frameworks
- https://custom-elements-everywhere.com/提供了一张列表,说明各JS框架对Web组件的兼容度。
-
Web Component Criticisms and Issues
-
Styling Difficulties
- 或可以不适用Shadow DOM
- 等等
-
Ignored Inputs
- Shadown DOM内部的Form元素不会自动关联到上级表单
- 早期需要添加隐藏域属到页面,然后使用FormData接口来更新量值
- 新的ElementInternals interface运行加钩子,是Chrome先行的
- 文中有一些例子
-
-
Summary
MDN
Web Components
- Web组件是一套技术,用于创建可重用的自定义元素
-
Concepts and usage
- 三大技术
- Custom elements
- Shadow DOM
- HTML templates
- 创建web组件的途径一般是这样的:
- 创建一个标类
- 注册到
CustomElementRegistry.define()
- 如果有需要,通过
Element.attachShadow()
添加Shadow DOM - 如果有需要,使用
<template>
和<slot>
- 三大技术
-
Tutorials
- 针对三大技术的教程
-
Reference
- (过)
-
Examples
-
See also
- 参考项目