插槽是Vue.js中一个强大的功能,允许你在组件中预留位置,让父组件可以插入自定义内容。以下是插槽的主要使用方法:
基本插槽
<!-- 子组件 ChildComponent.vue -->
<template>
<div>
<h2>子组件标题</h2>
<slot></slot> <!-- 这里是插槽位置 -->
</div>
</template>
<!-- 父组件使用 -->
<child-component>
<p>这是插入到插槽中的内容</p>
</child-component>
具名插槽
<!-- 子组件 Layout.vue -->
<template>
<div>
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot> <!-- 默认插槽 -->
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
<!-- 父组件使用 -->
<layout>
<template v-slot:header>
<h1>这是页眉</h1>
</template>
<p>这是主内容</p>
<template v-slot:footer>
<p>这是页脚</p>
</template>
</layout>
作用域插槽
允许子组件向插槽传递数据:
<!-- 子组件 TodoList.vue -->
<template>
<ul>
<li v-for="(item, index) in items" :key="index">
<slot :item="item" :index="index"></slot>
</li>
</ul>
</template>
<!-- 父组件使用 -->
<todo-list :items="todos">
<template v-slot:default="slotProps">
<span>{{ slotProps.index + 1 }}. {{ slotProps.item.text }}</span>
</template>
</todo-list>
缩写语法
v-slot:header
可以缩写为#header
- 默认插槽可以缩写为
#default
<layout>
<template #header>
<h1>缩写语法</h1>
</template>
<p>默认内容</p>
<template #footer>
<p>页脚内容</p>
</template>
</layout>
动态插槽名
<base-layout>
<template v-slot:[dynamicSlotName]>
...
</template>
</base-layout>
插槽提供了灵活的组件内容分发机制,是构建可复用组件的重要工具。