Web 组件是构建可重用、模块化 HTML 组件的强大工具。以下是一些基本概念和示例,帮助您开始使用 Web 组件。

基本概念

  • 自定义元素:Web 组件的核心,允许您创建新的 HTML 标签。
  • 影子 DOM:提供一种封装和隔离组件内部 DOM 的方式。
  • 属性绑定:将组件属性与组件内部状态绑定。

示例

假设我们要创建一个简单的按钮组件。

<template>
  <button id="myButton">点击我</button>
</template>

<script>
  class MyButton extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: 'open' });
      this.shadowRoot.innerHTML = `
        <style>
          button {
            padding: 10px 20px;
            font-size: 16px;
            color: white;
            background-color: blue;
            border: none;
            border-radius: 5px;
          }
        </style>
        <button id="myButton">点击我</button>
      `;
    }
  }

  customElements.define('my-button', MyButton);
</script>

在上面的代码中,我们定义了一个名为 my-button 的自定义元素,并为其添加了一些样式。

扩展阅读

更多关于 Web 组件的信息,请参阅以下链接:

Web 组件示例