javascript Web Components是什么_如何创建自定义HTML元素?

admin 百科 12
Web Components 是浏览器原生支持的可复用、封装良好的自定义 HTML 元素标准,由 Custom Elements、Shadow DOM 和 HTML Templates 三部分组成,不依赖框架,适用于跨技术栈的基础组件开发。

javascript Web Components是什么_如何创建自定义HTML元素?-第1张图片-佛山资讯网

Web Components 是一套浏览器原生支持的技术标准,让你能创建可复用、封装良好的自定义 HTML 元素。它不是框架,不依赖 React 或 Vue,而是直接基于 HTML、CSS 和 JavaScript 构建的“真正”的组件。

核心三部分:Custom Elements + Shadow DOM + HTML Templates

Web Components 由三个关键技术组成,缺一不可:

  • Custom Elements:定义新标签名(如 <my-button></my-button>),并绑定 JS 类行为
  • Shadow DOM:为组件提供样式和结构的私有作用域,避免全局污染
  • HTML Templates<template></template>):声明式地定义组件结构,内容默认不渲染,适合复用

从零创建一个自定义按钮元素

下面是一个完整、可运行的示例,实现带点击计数的 <counter-button></counter-button>

class CounterButton extends HTMLElement {
  constructor() {
    super();
    // 创建 Shadow DOM(闭合模式,外部无法访问内部节点)
    const shadow = this.attachShadow({ mode: 'closed' });

    // 定义模板结构(也可用 innerHTML,但 template 更语义化)
    const template = document.createElement('template');
    template.innerHTML = `
      <style>
        button { 
          background: #007bff; 
          color: white; 
          border: none; 
          padding: 8px 16px; 
          border-radius: 4px; 
          cursor: pointer;
        }
        button:hover { background: #0056b3; }
      </style>
      <button><slot>Click me</slot></button>
      <span>Count: <span id="count">0</span></span>
    `;

    // 克隆模板内容并挂载到 shadow root
    shadow.appendChild(template.content.cloneNode(true));

    // 初始化计数器状态
    this.count = 0;
    this.$countEl = shadow.getElementById('count');
    this.$button = shadow.querySelector('button');

    // 绑定事件
    this.$button.addEventListener('click', () => {
      this.count++;
      this.$countEl.textContent = this.count;
      // 可选:派发自定义事件供外部监听
      this.dispatchEvent(new CustomEvent('count-change', { detail: this.count }));
    });
  }

  // 属性变更时触发(需配合 static observedAttributes)
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === 'disabled' && newValue !== null) {
      this.$button.disabled = true;
    } else if (name === 'disabled' && newValue === null) {
      this.$button.disabled = false;
    }
  }

  // 声明要监听的属性(必须是字符串数组)
  static get observedAttributes() {
    return ['disabled'];
  }
}

// 向浏览器注册自定义元素(标签名必须含短横线)
customElements.define('counter-button', CounterButton);

登录后复制

使用方式就像普通 HTML 元素一样:

标签: css vue react javascript java html js 前端 node 浏览器 app ai

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~