首页/ 学科题库/ vue/ 插槽
vue 实战教程

插槽

2026-05-20 约 6 分钟 juanwangdev

插槽

插槽是组件内容分发的机制。

默认插槽

子组件

vue
<template>
  <div class="card">
    <slot></slot>
  </div>
</template>

父组件

vue
<CardComponent>
  <p>这是插入的内容</p>
</CardComponent>

具名插槽

子组件

vue
<template>
  <div>
    <header><slot name="header"></slot></header>
    <main><slot></slot></main>
    <footer><slot name="footer"></slot></footer>
  </div>
</template>

父组件

vue
<LayoutComponent>
  <template #header>
    <h1>标题</h1>
  </template>
  <template #footer>
    <p>页脚</p>
  </template>
  <p>主体内容</p>
</LayoutComponent>

作用域插槽

子组件传递数据给插槽内容:

子组件

vue
<template>
  <ul>
    <li v-for="item in items">
      <slot :item="item"></slot>
    </li>
  </ul>
</template>

父组件

vue
<ListComponent :items="users">
  <template #default="{ item }">
    <span>{{ item.name }}</span>
  </template>
</ListComponent>

后备内容

vue
<slot>默认内容(父组件未提供时显示)</slot>

作用域插槽是实现渲染函数和自定义列表组件的关键。

要点总结

  • 默认插槽:单个内容插入
  • 具名插槽:多个内容区域
  • 作用域插槽:子组件传递数据给父组件插槽内容
  • 后备内容:提供默认显示
想在手机上练这篇的配套题目?
使用微信 卷王开发者小程序/App,首页顶部扫一扫识别下方二维码,即可解锁本讲对应真题与错题本。
了解产品 App
← 上一篇 组件样式作用域 下一篇 → 生命周期概述