web component ui组件库
沸点数:25
作者:madama
生成时间:2025-04-08 10:49:42
来源:https://doc.ciilii.com/
参考资料
web component ui组件库
Web Component UI 组件库详细说明
基本概念
Web Components 是一组 Web 平台 API,允许创建可重用的自定义元素,其功能封装在代码的其余部分之外。
核心技术
Custom Elements:定义新HTML元素
Shadow DOM:封装样式和标记
HTML Templates:定义可复用的标记结构
ES Modules:实现代码的模块化和复用
安装方法
npm install @webcomponents/webcomponentsjs
或通过CDN引入:
<script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.4.3/webcomponents-bundle.js"></script>
基本示例
1. 定义自定义元素
class MyButton extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
button {
padding: 8px 16px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
<button><slot></slot></button>
`;
}
}
customElements.define('my-button', MyButton);2. 使用自定义元素
<my-button>Click Me</my-button>
高级功能示例
带属性的组件
class MyAvatar extends HTMLElement {
static get observedAttributes() {
return ['src', 'alt'];
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
img {
width: 50px;
height: 50px;
border-radius: 50%;
object-fit: cover;
}
</style>
<img>
`;
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'src') {
this.shadowRoot.querySelector('img').src = newValue;
}
if (name === 'alt') {
this.shadowRoot.querySelector('img').alt = newValue;
}
}
}
customElements.define('my-avatar', MyAvatar);使用:
<my-avatar src="user.jpg" alt="User Profile"></my-avatar>
事件处理示例
class MyDialog extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
.dialog {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background: white;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
z-index: 1000;
}
.close {
position: absolute;
top: 10px;
right: 10px;
cursor: pointer;
}
</style>
<div class="dialog">
<span class="close">×</span>
<slot></slot>
</div>
`;
this.shadowRoot.querySelector('.close').addEventListener('click', () => {
this.dispatchEvent(new CustomEvent('close'));
this.remove();
});
}
}
customElements.define('my-dialog', MyDialog);使用:
const dialog = document.createElement('my-dialog');
dialog.textContent = 'This is a dialog message';
document.body.appendChild(dialog);
dialog.addEventListener('close', () => {
console.log('Dialog closed');
});流行的Web Component UI库
LitElement (由Google维护)
Shoelace (纯Web Components实现)
Vaadin Components
Elix (高质量UI组件)
Material Web Components (Google Material Design实现)
作者:王壹杰
时间:2025-04-08 10:49:42
来源:https://doc.ciilii.com/
时间:2025-04-08 10:49:42
来源:https://doc.ciilii.com/
