全书目录

第三篇:Vue 完全指南 —— 新城区商业街宇宙

第十章:插槽 —— 毛坯商铺,装修风格交给外部

1 分钟 75 字 第 80 / 962 个阅读单元

组件有时候不应该把一切写死。它更适合提供一个“壳”,把内部某些区域留给外部定制,这就是 slots

vue
<!-- ShopPanel.vue -->
<template>
  <section class="panel">
    <header>
      <slot name="title">默认标题</slot>
    </header>

    <main>
      <slot />
    </main>

    <footer>
      <slot name="footer">默认页脚</slot>
    </footer>
  </section>
</template>
vue
<!-- Parent.vue -->
<template>
  <ShopPanel>
    <template #title>
      <h2>Vue 书店</h2>
    </template>

    <p>主营:前端工程、状态管理、SSR。</p>

    <template #footer>
      <button>进入店铺</button>
    </template>
  </ShopPanel>
</template>

插槽的本质就是:组件提供结构,使用者提供内容。