首先插槽分为匿名插槽、具名插槽和作用域插槽
先准备两个页面和一个组件
list.vue组件
<template>
<div>
<div>组件内容区域1</div>
<div>组件内容区域2</div>
</div>
</template>
a.vue页面
<script setup>
import List from './components/list.vue'
</script>
<template>
<div class="content">
这是aaa页面
<List></List>
</div>
</template>
b.vue页面
<script setup>
import List from './components/list.vue'
</script>
<template>
<div class="content">
这是bbb页面
<List></List>
</div>
</template>
然后我们在list组件中使用插槽
<template>
<div>
<div>组件内容区域1</div>
<div>组件内容区域2</div>
<slot></slot>
</div>
</template>
此时页面还没有什么变化,我们修改a页面
<script setup>
import List from './components/list.vue'
</script>
<template>
<div class="content">
这是aaa页面
<List>
<div style="color: red;">给插槽插入内容</div>
</List>
</div>
</template>
然后运行a页面效果
b页面效果
如果我们想在组件里其他位置再插入内容,就可以使用具名插槽了
修改a页面
<script setup>
import List from './components/list.vue'
</script>
<template>
<div class="content">
这是aaa页面
<List>
<template #header>
<div style="color: red;">在组件顶部插入内容</div>
</template>
<template #footer>
<div style="color: red;">给组件底部插入内容</div>
</template>
</List>
</div>
</template>
修改list组件
<template>
<div>
<slot name="header"></slot>
<div>组件内容区域1</div>
<div>组件内容区域2</div>
<slot name="footer"></slot>
</div>
</template>
a页面运行效果
作用域插槽就是在具名插槽上再传入值,比如我们想要在b页面显示list里的数据,需要list组件将值传给b页面
修改b页面和list组件
<script setup>
import List from './components/list.vue'
</script>
<template>
<div class="content">
这是bbb页面
<List>
<template #footer="{arr}">
<div v-for="(item, index) in arr" :key="index">{{ item }}</div>
</template>
</List>
</div>
</template>
<script setup>
import { ref } from 'vue'
const arr=ref(['a','b','c','d'])
</script>
<template>
<div>
<slot name="header"></slot>
<div>组件内容区域1</div>
<div>组件内容区域2</div>
<slot name="footer" :arr="arr"></slot>
</div>
</template>
b页面效果如下