一、默认插槽(Default Slot)
默认插槽是最基础的插槽类型,用于在组件中预留内容插入点。当父组件向子组件传递内容时,如果没有指定插槽名称,就会使用默认插槽。
html
<!-- 子组件 ChildComponent.vue -->
<template>
<div class="child-wrapper">
<h3>子组件标题</h3>
<slot>默认内容(可选)</slot>
</div>
</template>
<!-- 父组件 -->
<template>
<ChildComponent>
<p>这是插入到默认插槽的内容</p>
</ChildComponent>
</template>
使用场景
-
通用容器组件
-
卡片组件
-
布局组件的基础结构
二、具名插槽(Named Slot)
具名插槽允许在一个组件中定义多个插槽,每个插槽都有特定的名称。父组件可以通过 v-slot 指令将内容精确地插入到对应的插槽位置。
html
<!-- 子组件 LayoutComponent.vue -->
<template>
<div class="layout">
<header>
<slot name="header">默认头部</slot>
</header>
<main>
<slot>默认主体内容</slot>
</main>
<footer>
<slot name="footer">默认底部</slot>
</footer>
</div>
</template>
<!-- 父组件 -->
<template>
<LayoutComponent>
<!-- 简写语法 -->
<template #header>
<h1>自定义头部内容</h1>
</template>
<!-- 默认插槽 -->
<p>主体内容</p>
<!-- 完整语法 -->
<template v-slot:footer>
<p>自定义底部内容</p>
</template>
</LayoutComponent>
</template>
使用场景
-
复杂布局组件
-
模态框组件(标题、内容、按钮区域)
-
表格组件(表头、表体、表尾)
高级用法:解构和重命名
html
<!-- 解构用法 -->
<ListComponent v-slot="{ item: person, index: idx }">
<div>{{ idx }} - {{ person.name }}</div>
</ListComponent>
<!-- 设置默认值 -->
<ListComponent v-slot="{ item = { name: '默认值' } }">
<div>{{ item.name }}</div>
</ListComponent>
使用场景
-
表格组件(自定义列渲染)
-
列表组件(自定义列表项)
-
树形组件(自定义节点渲染)
-
任何需要灵活渲染的组件
四、插槽实战技巧
1. 插槽默认值
html
<!-- 子组件 -->
<slot name="actions">
<button>默认按钮</button>
</slot>
2. 动态插槽名
html
<template v-slot:[dynamicSlotName]>
动态插槽内容
</template>
3. 插槽嵌套
html
<!-- 复杂布局 -->
<template #header>
<div class="complex-header">
<slot name="header-content">
<h2>默认标题</h2>
</slot>
</div>
</template>
4. 性能优化
-
避免在插槽中进行复杂计算
-
使用计算属性处理插槽数据
-
合理使用
v-memo优化列表渲染
五、常见误区和最佳实践
误区1:混淆插槽作用域
html
<!-- ❌ 错误:在父组件中直接访问子组件的数据 -->
<ChildComponent>
<p>{{ childData }}</p> <!-- 无法访问 -->
</ChildComponent>
<!-- ✅ 正确:使用作用域插槽 -->
<ChildComponent v-slot="{ childData }">
<p>{{ childData }}</p>
</ChildComponent>
误区2:插槽命名冲突
html
<!-- 避免使用保留字作为插槽名 -->
<slot name="default"></slot> <!-- ❌ 不推荐 -->
<slot></slot> <!-- ✅ 推荐 -->
最佳实践
-
语义化命名:插槽名称要有明确的语义
-
提供默认值:为插槽提供合理的默认内容
-
文档化:在组件文档中清晰说明每个插槽的作用
-
类型安全:在 TypeScript 中为插槽 props 定义类型
六、总结对比
| 插槽类型 | 特点 | 使用场景 | 语法复杂度 |
|---|---|---|---|
| 默认插槽 | 简单直接 | 基础内容插入 | ⭐ |
| 具名插槽 | 多位置插入 | 复杂布局 | ⭐⭐ |
| 作用域插槽 | 数据暴露 | 高度自定义 | ⭐⭐⭐ |