← 中文资源

简体中文版本

使用 slot 组合 Web Component

在 Shadow DOM 模板中定义具名与默认 slot,让 custom-card 接收标题、正文和页脚内容,并展示默认回退文本。

阅读英文原文

功能说明

示例定义一个 custom-card 自定义元素:模板中包含 header、默认和 footer 三个插入点,使用方通过 slot="header"、无 slot 的默认内容以及 slot="footer" 向卡片分发标题、正文和操作按钮。没有提供内容的插槽会显示模板里的默认文本。它适合构建布局组件、弹窗壳和可复用卡片。

关键代码

<template id="card-template">
  <div class="card">
    <div class="card-header">
      <slot name="header">Default Header</slot>
    </div>
    <div class="card-body">
      <slot></slot>
    </div>
    <div class="card-footer">
      <slot name="footer">Default Footer</slot>
    </div>
  </div>
</template>

<custom-card>
  <span slot="header">My Card Title</span>
  <p>This goes in the default slot (body).</p>
  <button slot="footer">Action Button</button>
</custom-card>
class CustomCard extends HTMLElement {
  constructor() {
    super();
    const template = document.getElementById('card-template');
    const shadow = this.attachShadow({ mode: 'open' });
    shadow.appendChild(template.content.cloneNode(true));
  }
}
customElements.define('custom-card', CustomCard);

构造函数克隆模板内容并放入影子根,<slot> 元素留在影子树中作为占位,使用方写在 <custom-card> 标签内的内容会按 slot 名称投影到对应位置。没有 slot 属性的子节点进入默认插槽,插槽内的文本只在没有分发内容时显示。

使用注意

第二个卡片中的图片写了 slot="body",但模板只定义了 header、默认和 footer 三个插槽,没有名为 body 的插槽,因此该图片不会被投影到卡片正文,也不会出现在默认插槽中。使用 slot 时必须确保名称与模板一致,且大小写要匹配。插槽内容仍属于使用方 DOM,影子树内的样式无法直接选中它,需要借助 ::slotted() 或外部样式。模板中的默认文本只在插槽为空时出现,不能同时与分发内容共存。attachShadow 的 open 模式允许外部脚本访问影子根,便于调试但不提供强封装。

验证方式

在 DevTools 中展开两个 custom-card 的影子树,确认标题、正文和页脚分别落到正确位置,并检查第二个卡片的图片是否真的被渲染。再删除某个 slot 属性或改错名称,观察内容是否退回默认插槽,并用 ::slotted() 测试能否对分发内容施加样式。