默认插槽
默认插槽是最基本的插槽类型,用于接收父组件传递的任意内容。
子组件 (ChildComponent.vue)
<template>
<div>
<h2>子组件标题</h2>
<!-- 默认插槽 -->
<slot></slot>
</div>
</template>
<script setup>
// Composition API 不需要额外代码处理默认插槽
</script>
父组件使用
<template>
<ChildComponent>
<p>这是插入到默认插槽的内容</p>
</ChildComponent>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue'
</script>
具名插槽
具名插槽允许你有多个插槽,并通过名称区分它们。
子组件 (NamedSlots.vue)
<template>
<div>
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot> <!-- 默认插槽 -->
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
<script setup>
// 不需要额外代码处理具名插槽
</script>
父组件使用
<template>
<NamedSlots>
<template v-slot:header>
<h1>这是头部内容</h1>
</template>
<p>这是默认插槽的内容</p>
<template v-slot:footer>
<p>这是页脚内容</p>
</template>
</NamedSlots>
</template>
<script setup>
import NamedSlots from './NamedSlots.vue'
</script>
作用域插槽
作用域插槽允许子组件向插槽传递数据,父组件可以访问这些数据。
子组件 (ScopedSlot.vue)
<template>
<ul>
<li v-for="item in items" :key="item.id">
<!-- 向插槽传递数据 -->
<slot :item="item" :index="index"></slot>
</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
const items = ref([
{ id: 1, name: '项目1' },
{ id: 2, name: '项目2' },
{ id: 3, name: '项目3' }
])
</script>
父组件使用
<template>
<ScopedSlot>
<!-- 使用解构语法接收作用域数据 -->
<template v-slot="{ item, index }">
{{ index + 1 }}. {{ item.name }}
</template>
</ScopedSlot>
</template>
<script setup>
import ScopedSlot from './ScopedSlot.vue'
</script>
动态插槽名
Vue 3 支持动态插槽名
<template>
<DynamicSlot>
<template v-slot:[dynamicSlotName]>
动态插槽内容
</template>
</DynamicSlot>
</template>
<script setup>
import { ref } from 'vue'
const dynamicSlotName = ref('header')
</script>
使用 useSlots()
来访问插槽内容
<script setup>
import { useSlots } from 'vue'
const slots = useSlots()
// 检查某个插槽是否存在
if (slots.header) {
console.log('header 插槽存在')
}
</script>