示例工程 34-template-slot

34-template-slot/demo-02-slots/index.html

html · 1.9 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>
    <style>
      body { margin: 0; padding: 32px; background: #f8fafc; color: #0f172a; font-family: system-ui, sans-serif; line-height: 1.7; }
      .box { max-width: 720px; margin-bottom: 16px; padding: 18px; border: 1px solid #e2e8f0; border-radius: 12px; background: #fff; }
      h1 { margin: 0 0 16px; font-size: 28px; }
      h2 { margin: 0 0 8px; font-size: 17px; }
      p { margin: 0 0 10px; color: #334155; }
      .card { display: block; margin: 10px 0; padding: 14px; border: 1px solid #e2e8f0; border-radius: 10px; }
      code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, monospace; }
    </style>
  </head>
  <body>
    <h1>slot</h1>

    <div class="box">
      <h2>命名 slot 与默认 slot</h2>
      <div class="card">
        <template shadowrootmode="open">
          <style>
            h2 { margin: 0 0 6px; font-size: 18px; }
            .meta { margin-top: 6px; color: #64748b; font-size: 13px; }
          </style>
          <h2><slot name="title">默认标题</slot></h2>
          <div><slot>默认内容</slot></div>
          <div class="meta"><slot name="meta">默认说明</slot></div>
        </template>

        <span slot="title">组件标题</span>
        <p>没有 slot 属性的内容进入默认 slot。</p>
        <span slot="meta">2026-11-28</span>
      </div>
    </div>

    <div class="box">
      <h2>回退内容</h2>
      <div class="card">
        <template shadowrootmode="open">
          <h2><slot name="title">未命名卡片</slot></h2>
          <p><slot>这个组件还没有内容。</slot></p>
        </template>
      </div>
      <p>外部没有提供内容时,slot 显示自己的文字。</p>
    </div>
  </body>
</html>