插槽
插槽是组件内容分发的机制。
默认插槽
子组件
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>
作用域插槽是实现渲染函数和自定义列表组件的关键。
要点总结
- 默认插槽:单个内容插入
- 具名插槽:多个内容区域
- 作用域插槽:子组件传递数据给父组件插槽内容
- 后备内容:提供默认显示
📝 发现内容有误?点击此处直接编辑