Web Component
什么是Web Component?
Web Component是一组Web原生API的统称
为什么有Web Component?
为了解决代码复用、组件自定义、复用管理的问题
Web Component能干什么?
可以允许开发者创建可复用的自定义元素,跨框架使用
Web Component有什么核心知识点?
-
Custom element(自定义元素)首先Web Component允许开发者在HTML元素基础上自定义元素
所以需要自己定义一个类,这个类可以有两种继承方式
自定义内置元素:继承自标准HTML元素,如HTMLImageElement或HTMLParagraphElement
独立自定义元素:继承自HTML元素基类HTMLElement
-
Shadow DOM(影子DOM)再者自定义元素需要封装,由于可以在网页的任何地方使用,所以需要与外界隔离,保持元素的功能私有
shadow root可以将自定义元素与页面上其他代码隔离,保证不同的部分不会混在一起,使代码更加干净、整洁
这里可以调用DOM元素身上的方法
attachShadow()来给Web Component开启影子DOM,自定义元素内部的HTLM结构会存在于#shadow-root,而不会在真实的DOM树中出现 -
HTML template(HTML 模版)可以通过
<template>模版共用重复结构
怎么创建一个web component
- 创建一个类或函数来指定web组件的功能
- 使用CustomElementRegistry.define()注册自定义元素,传递要定义的元素名称、指定元素功能的类,以及一些可选项
- 使用Element.attachShadow()方法将一个shadow DOM附加到自定义元素上,可以使用DOM方法向shadow DOM中添加自元素、事件监听器等
- 如果需要,使用
<template>和<slot>定义HTML模版 - 在页面使用自定义元素
简单实现
创建main.js和index.html
main.js
// web component
class WordCount extends HTMLParagraphElement {
constructor() {
super();
// 获取父节点
const wcParent = this.parentNode;
// 创建shadow root
const shadow = this.attachShadow({ mode: 'open' });
// 创建文本
const text = document.createElement('span');
// 设置文本内容,父节点的单词个数
const count = `Words:${countWords(wcParent)}`;
text.textContent = count;
shadow.appendChild(text);
// 计算父节点的单词个数并实时更新
function countWords(node) {
const text = node.innerText || node.textContent;
return text.trim().split(/\s+/g).filter(
word => word.trim().length > 0
).length;
// 更新
setInterval(function() {
const count = `Words:${countWords(wcParent)}`;
this.text.textContent = count;
}, 200);
}
}
}
// 定义元素(元素名,类名,扩展自内部元素)
customElements.define('word-count', WordCount, {extends: 'p'});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>word count web component</title>
</head>
<body>
<h1>word count</h1>
<article contenteditable="">
One of the key features of web components is the ability to create custom elements: that is,
HTML elements whose behavior is defined by the web developer, that extend the set of elements available in the browser.
This article introduces custom elements, and walks through some examples.
<p is="word-count"></p>
</article>
<script src="main.js"></script>
</body>
</html>
效果