全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 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>

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

要点总结

  • 默认插槽:单个内容插入
  • 具名插槽:多个内容区域
  • 作用域插槽:子组件传递数据给父组件插槽内容
  • 后备内容:提供默认显示

📝 发现内容有误?点击此处直接编辑

← 上一篇 动态组件与异步组件
下一篇 → 组件基本概念
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库