示例工程 44-slots-templates

44-slots-templates/app/index.html

html · 8.6 KB

运行:slot 与模板 · 组合而不是继承

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>slot 与模板 · 组合而不是继承</title>
    <meta name="description" content="具名插槽、默认插槽、回退内容、slotchange 与 template 克隆。" />
    <style>
      * { box-sizing: border-box; }
      body {
        margin: 0;
        min-height: 100vh;
        padding: 30px 20px 40px;
        background: #f8fafc;
        color: #0f172a;
        font-family: system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
        line-height: 1.7;
      }
      .page { width: min(100%, 800px); margin: 0 auto; }
      .site-header { display: flex; justify-content: space-between; gap: 16px; padding-bottom: 14px; border-bottom: 1px solid #e2e8f0; }
      .brand { font-weight: 700; letter-spacing: 0.14em; font-size: 13px; }
      nav a { color: #2563eb; font-size: 13px; text-decoration: none; }
      nav a + a { margin-left: 14px; }
      main { padding: 22px 0; }
      .eyebrow { margin: 0; color: #64748b; font-size: 11px; letter-spacing: 0.18em; }
      h1 { margin: 6px 0 10px; font-size: clamp(30px, 6vw, 42px); line-height: 1.15; }
      .lead { margin: 0 0 18px; color: #334155; font-size: 17px; }
      section { margin-top: 22px; padding-top: 16px; border-top: 1px solid #e2e8f0; }
      h2 { margin: 0 0 10px; font-size: 21px; }
      p { margin: 0 0 12px; color: #334155; }
      ul { margin: 8px 0 12px; padding-left: 24px; color: #334155; }
      li + li { margin-top: 4px; }
      .row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin: 12px 0; }
      x-card { display: block; }
      x-inspector { display: block; }
      code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, Menlo, monospace; font-size: 0.92em; }
      pre { margin: 10px 0 0; padding: 14px; overflow-x: auto; border-radius: 10px; background: #0f172a; color: #e2e8f0; font-size: 12px; line-height: 1.7; }
      pre code { padding: 0; background: none; color: inherit; }
      .note { padding: 12px 14px; border-left: 4px solid #2563eb; border-radius: 6px; background: #eff6ff; color: #1e3a8a; font-size: 14px; }
      footer { margin-top: 24px; padding-top: 14px; border-top: 1px solid #e2e8f0; color: #64748b; font-size: 12px; }
      @media (max-width: 560px) {
        body { padding: 18px 14px 32px; }
        .site-header { flex-direction: column; }
        .row { grid-template-columns: 1fr; }
      }
    </style>
  </head>
  <body>
    <div class="page">
      <header class="site-header">
        <span class="brand">SLOTS / 2026</span>
        <nav aria-label="页内导航">
          <a href="#named">具名</a>
          <a href="#fallback">回退</a>
          <a href="#template">模板</a>
          <a href="#inspect">检查</a>
        </nav>
      </header>

      <main>
        <p class="eyebrow">LESSON / 44</p>
        <h1>slot 与模板</h1>
        <p class="lead">
          把结构交给组件,把内容留给使用者。插槽是「填充位」,模板是「可复制的结构」,两者组合出真正可组合的组件。
        </p>

        <section id="named">
          <h2>1. 具名与默认插槽</h2>
          <p>同一张卡片,标题、正文、操作区分别填入不同位置。</p>

          <div class="row">
            <x-card>
              <h3 slot="header">构建通过</h3>
              <p>最近一次构建用时 42 秒,没有告警。</p>
              <a slot="footer" href="#named">查看日志</a>
            </x-card>

            <x-card>
              <h3 slot="header">等待审校</h3>
              <p>两篇文档已提交,等待第二位审校人。</p>
            </x-card>
          </div>

          <pre><code>&lt;x-card&gt;
  &lt;h3 slot="header"&gt;构建通过&lt;/h3&gt;
  &lt;p&gt;最近一次构建用时 42 秒。&lt;/p&gt;
  &lt;a slot="footer" href="#named"&gt;查看日志&lt;/a&gt;
&lt;/x-card&gt;</code></pre>
        </section>

        <section id="fallback">
          <h2>2. 回退内容</h2>
          <p>没有填 footer 时,显示组件自带的「暂无操作」,而不是一片空白。</p>
          <x-card>
            <p>这张卡片只填了默认插槽,标题与操作区都走回退。</p>
          </x-card>
          <p class="note">回退内容只在没有对应内容时出现;一旦填入,整段回退被替换。</p>
        </section>

        <section id="template">
          <h2>3. 模板克隆</h2>
          <p><code>&lt;template&gt;</code> 只解析一次,每个实例克隆一份,结构稳定、成本低。</p>
          <ul>
            <li>卡片结构来自 <code>#card-tpl</code>;</li>
            <li>克隆后填入插槽,不改模板本身;</li>
            <li>模板内容不会出现在页面上。</li>
          </ul>
        </section>

        <section id="inspect">
          <h2>4. 插槽检查</h2>
          <p>下面的组件统计三个插槽各分配了多少个元素,并在变化时更新。</p>

          <x-inspector>
            <span slot="one">优先</span>
            <span slot="one">高</span>
            <span slot="two">今天</span>
            <span>默认内容</span>
          </x-inspector>
        </section>
      </main>

      <footer>
        <p>示例数据为虚构,仅用于教学。</p>
      </footer>
    </div>

    <template id="card-tpl">
      <style>
        :host { display: block; }
        article { height: 100%; padding: 14px 16px; border: 1px solid #e2e8f0; border-radius: 10px; background: #fff; }
        header { margin-bottom: 10px; }
        ::slotted([slot="header"]) { margin: 0; font-size: 17px; color: #0f172a; }
        .body { color: #334155; font-size: 14px; }
        .body ::slotted(p) { margin: 0 0 8px; }
        footer { margin-top: 12px; padding-top: 10px; border-top: 1px solid #e2e8f0; font-size: 13px; }
        .fallback { color: #94a3b8; }
        ::slotted([slot="footer"]) { color: #2563eb; }
      </style>
      <article>
        <header><slot name="header"><span class="fallback">未命名卡片</span></slot></header>
        <div class="body"><slot></slot></div>
        <footer><slot name="footer"><span class="fallback">暂无操作</span></slot></footer>
      </article>
    </template>

    <template id="inspector-tpl">
      <style>
        :host { display: block; }
        .grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin-bottom: 10px; }
        .cell { padding: 8px 10px; border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; font-size: 13px; }
        .cell span { color: #64748b; }
        output { display: block; font-size: 20px; font-weight: 700; font-variant-numeric: tabular-nums; }
        .hint { color: #64748b; font-size: 13px; }
      </style>
      <div class="grid">
        <div class="cell"><span>one</span><output data-one>0</output></div>
        <div class="cell"><span>two</span><output data-two>0</output></div>
        <div class="cell"><span>default</span><output data-default>0</output></div>
      </div>
      <p class="hint"><slot name="one"></slot><slot name="two"></slot><slot></slot></p>
    </template>

    <script>
      class XCard extends HTMLElement {
        constructor() {
          super();
          const tpl = document.getElementById("card-tpl");
          this.attachShadow({ mode: "open" }).append(tpl.content.cloneNode(true));
        }
      }
      customElements.define("x-card", XCard);

      class XInspector extends HTMLElement {
        constructor() {
          super();
          const tpl = document.getElementById("inspector-tpl");
          this.attachShadow({ mode: "open" }).append(tpl.content.cloneNode(true));
        }

        connectedCallback() {
          const root = this.shadowRoot;
          this.slots = {
            one: root.querySelector('slot[name="one"]'),
            two: root.querySelector('slot[name="two"]'),
            default: root.querySelector("slot:not([name])"),
          };
          this.outputs = {
            one: root.querySelector("[data-one]"),
            two: root.querySelector("[data-two]"),
            default: root.querySelector("[data-default]"),
          };
          for (const name of Object.keys(this.slots)) {
            this.slots[name].addEventListener("slotchange", () => this.update(name));
            this.update(name);
          }
        }

        update(name) {
          const count = this.slots[name].assignedElements({ flatten: true }).length;
          this.outputs[name].textContent = String(count);
        }
      }
      customElements.define("x-inspector", XInspector);
    </script>
  </body>
</html>