WebComponent创建

如何创建和部署 Web Component

Web Components 是一套浏览器原生支持的组件化技术,允许创建可复用的自定义 HTML 元素。以下是完整指南:


一、创建 Web Component(4 步实现)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 1. 定义组件类(继承 HTMLElement)
class MyComponent extends HTMLElement {
constructor() {
super();

// 2. 创建 Shadow DOM(封装样式/结构)
const shadow = this.attachShadow({ mode: 'open' });

// 3. 定义模板
const template = document.createElement('template');
template.innerHTML = `
<style>
/* 封装样式 */
:host { display: block; padding: 20px; }
button { background: #4CAF50; color: white; }
</style>
<div class="container">
<button>点击计数: <span id="count">0</span></button>
</div>
`;

// 4. 克隆模板并挂载
shadow.appendChild(template.content.cloneNode(true));

// 添加交互逻辑
const countSpan = shadow.getElementById('count');
let count = 0;
shadow.querySelector('button').addEventListener('click', () => {
countSpan.textContent = ++count;
this.dispatchEvent(new CustomEvent('count-changed', { detail: count }));
});
}
}

// 注册自定义元素
customElements.define('my-component', MyComponent);

二、使用 Web Component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
<script src="my-component.js" defer></script>
</head>
<body>
<my-component></my-component>

<script>
// 监听自定义事件
document.querySelector('my-component')
.addEventListener('count-changed', e => {
console.log('当前计数:', e.detail);
});
</script>
</body>
</html>

三、部署策略(3 种方式)

  1. 直接引入(快速部署)

    1
    2
    3
    4
    5
    <!-- 本地文件 -->
    <script src="path/to/my-component.js"></script>

    <!-- CDN 托管 -->
    <script src="https://cdn.example.com/my-component.js"></script>
  2. NPM 包发布(团队协作)

    1
    2
    3
    # 发布步骤
    npm init
    npm publish --access public

    使用方安装:

    1
    npm install @yourname/my-component

    导入使用:

    1
    import '@yourname/my-component';
  3. HTML 模块化(现代浏览器)

    1
    2
    3
    4
    <script type="module">
    import { MyComponent } from './my-component.js';
    customElements.define('my-component', MyComponent);
    </script>

四、最佳实践

  1. 命名规范:必须包含连字符(如 my-component
  2. 响应式设计:在组件内使用 CSS 媒体查询
  3. 属性监听
    1
    2
    3
    4
    5
    6
    7
    static get observedAttributes() { return ['disabled']; }

    attributeChangedCallback(name, oldVal, newVal) {
    if (name === 'disabled') {
    this.toggleAttribute('disabled', newVal !== null);
    }
    }
  4. 浏览器兼容:添加 Web Components Polyfill(支持 IE11+)

五、完整生命周期

方法 触发时机
constructor() 元素创建时
connectedCallback() 插入 DOM 时
disconnectedCallback() 从 DOM 移除时
attributeChangedCallback() 属性变化时
adoptedCallback() 被移动到新文档时

六、示例:带属性的组件

1
2
3
4
5
6
7
8
9
10
11
class ColorBlock extends HTMLElement {
static get observedAttributes() { return ['color']; }

attributeChangedCallback(name, oldVal, newVal) {
if (name === 'color') {
this.style.backgroundColor = newVal;
}
}
}

customElements.define('color-block', ColorBlock);
1
<color-block color="#FF5733"></color-block>

七、调试技巧

  1. 在 Chrome DevTools 中启用:
    1
    Settings → Experiments → 勾选 "Web Components"
  2. 直接检查 Shadow DOM:
    1
    document.querySelector('my-component').shadowRoot

通过以上步骤,您可以创建出企业级可复用的组件。实际案例参考:GitHub 官方 Web Components 示例库