1.新建一个组件,在主页面中引入该主页,在组件中建立需要的插槽,然后在主页面中插入相应的内容,具体代码解释如下↓
匿名插槽和具名插槽
<template>
<div class="container">
<h1>我是插槽</h1>
<slotCom>
<template #header>
我往盒子上面插入
</template>
<template v-slot>
我往盒子中间插入
</template>
<template #footer>
我往盒子下方插入
</template>
</slotCom>
</div>
</template>
<script setup>
import { reactive, toRefs } from 'vue'
import slotCom from '@/components/slotCom'
</script>
<style lang="scss" scoped>
</style>
子页面
<template>
<div>
我是头,我使用的是具名插槽
<slot name="header"></slot>
</div>
<div>
我是中间,我使用的是匿名插槽
<slot></slot>
</div>
<div>我是尾,我也用的是具名插槽
<slot name="footer"></slot>
</div>
</template>
<script setup>
import { reactive, toRefs } from 'vue'
</script>
<style lang="scss" scoped>
div {
width: 90%;
height: 100px;
margin-left: 5%;
line-height: 100px;
border: 1px solid rgb(0, 0, 0);
margin-bottom: 10px;
text-align: center;
}
</style>
2.下面我们来看看作用域插槽,是子组件像父组件传递数据,从而填充父组件的内容
//这里是子组件
<template>
<div>
这里是作用域插槽
<span v-for="(item, index) in data" :key="index">
<slot :data="item" :index="index"></slot>
</span>
</div>
</template>
<script setup>
import { reactive, toRefs } from 'vue'
const data = reactive([
{ name: '作用域插槽来咯1', age: 201 },
{ name: '作用域插槽来咯2', age: 202 },
{ name: '作用域插槽来咯3', age: 203 },
])
</script>
<style lang="scss" scoped>
div {
width: 90%;
margin-left: 5%;
line-height: 100px;
border: 1px solid rgb(0, 0, 0);
margin-bottom: 10px;
text-align: center;
}
</style>
//这里是父组件接收
<template>
<div class="container">
<template v-slot="{data,index}">
<p>{{index}}---{{data.name}}----{{data.age}}</p>
</template>
</slotCom>
</div>
</template>
<script setup>
import { reactive, toRefs } from 'vue'
import slotCom from '@/components/slotCom'
</script>
<style lang="scss" scoped>
</style>