HTML5 Web Components实战:5个自定义元素开发技巧
核心价值: Web Components是浏览器原生支持的组件化方案。本文将展示5个实际开发中的高级应用场景,无需框架即可创建可复用的UI组件。
1. 基础自定义元素
创建简单的自定义元素:
// 定义自定义元素
class UserCard extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = `
<style>
.card {
border: 1px solid #ddd;
padding: 16px;
border-radius: 4px;
}
</style>
<div class="card">
<h3><slot name="name">默认姓名</slot></h3>
<p><slot name="email">默认邮箱</slot></p>
</div>
`;
}
}
// 注册自定义元素
customElements.define('user-card', UserCard);
2. 属性监听与响应
实现属性变化响应:
class ThemeButton extends HTMLElement {
static get observedAttributes() {
return ['theme'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'theme') {
this.updateTheme(newValue);
}
}
updateTheme(theme) {
this.style.backgroundColor = theme === 'dark' ? '#333' : '#eee';
this.style.color = theme === 'dark' ? '#fff' : '#333';
}
}
customElements.define('theme-button', ThemeButton);
3. 模板与插槽
使用template和slot:
<template id="tooltip-template">
<style>
.tooltip {
position: relative;
display: inline-block;
}
.tooltip-text {
visibility: hidden;
/* 更多样式... */
}
</style>
<div class="tooltip">
<slot></slot>
<span class="tooltip-text"><slot name="tooltip"></slot></span>
</div>
</template>
<script>
class MyTooltip extends HTMLElement {
constructor() {
super();
const template = document.getElementById('tooltip-template');
const content = template.content.cloneNode(true);
this.attachShadow({mode: 'open'}).appendChild(content);
}
}
customElements.define('my-tooltip', MyTooltip);
</script>
4. 自定义事件
组件间通信:
class RatingElement extends HTMLElement {
constructor() {
super();
// ...初始化代码
this.addEventListener('click', (e) => {
const rating = e.target.dataset.rating;
this.dispatchEvent(new CustomEvent('rating-change', {
detail: { rating },
bubbles: true
}));
});
}
}
// 使用
document.querySelector('rating-element')
.addEventListener('rating-change', (e) => {
console.log('评分:', e.detail.rating);
});
特性 | Web Components | 框架组件 |
---|---|---|
跨框架使用 | ✓ | × |
性能 | 高(原生) | 依赖框架 |
开发效率 | 中 | 高 |
5. 组合式组件
构建复杂组合组件:
class TabContainer extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = `
<style>
/* 标签样式 */
</style>
<div class="tabs">
<slot name="tab"></slot>
</div>
<div class="panels">
<slot name="panel"></slot>
</div>
`;
}
}
// 使用
<tab-container>
<button slot="tab">标签1</button>
<div slot="panel">内容1</div>
<button slot="tab">标签2</button>
<div slot="panel">内容2</div>
</tab-container>
Web Components为前端开发提供了原生组件化方案,特别适合需要跨框架使用或追求极致性能的场景。