vue slot实现
Vue Slot 实现方法
Vue 的插槽(Slot)是一种内容分发机制,允许父组件向子组件传递模板片段。以下是几种常见的插槽实现方式:
默认插槽
子组件通过 <slot> 标签定义插槽位置,父组件传递的内容会替换该标签。
子组件模板:
<div class="child-component">
<slot></slot>
</div>
父组件使用:
<child-component>
<p>这是插入到子组件的内容</p>
</child-component>
具名插槽
当需要多个插槽时,可以使用具名插槽。子组件通过 name 属性命名插槽,父组件使用 v-slot 指令指定内容插入位置。
子组件模板:
<div class="child-component">
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
父组件使用:

<child-component>
<template v-slot:header>
<h1>标题内容</h1>
</template>
<p>默认插槽内容</p>
<template v-slot:footer>
<p>页脚内容</p>
</template>
</child-component>
作用域插槽
当子组件需要向插槽传递数据时,可以使用作用域插槽。子组件在 <slot> 上绑定属性,父组件通过 v-slot 接收数据。
子组件模板:
<div class="child-component">
<slot :item="item" :index="index"></slot>
</div>
父组件使用:
<child-component>
<template v-slot:default="slotProps">
<p>第 {{ slotProps.index }} 项: {{ slotProps.item }}</p>
</template>
</child-component>
缩写语法
Vue 提供了插槽的缩写语法,使代码更简洁。

具名插槽缩写:
<template #header>
<h1>标题内容</h1>
</template>
作用域插槽缩写:
<template #default="{ item, index }">
<p>第 {{ index }} 项: {{ item }}</p>
</template>
动态插槽名
可以使用动态指令参数指定动态插槽名。
父组件使用:
<child-component>
<template #[dynamicSlotName]>
<p>动态插槽内容</p>
</template>
</child-component>
插槽使用场景
- 布局组件:通过插槽实现灵活的布局结构
- 可复用组件:允许父组件自定义部分内容
- 高阶组件:向包装的组件注入额外内容
- 列表渲染:自定义每个列表项的渲染方式
通过合理使用插槽,可以创建更灵活、更可复用的 Vue 组件。





