在自定义组件时,考虑到组件的复用性,往往会用到插槽,实际上就是在组件中提前预留位置,等后面使用的时候再填充过来
定义组件
定义如下的组件,名为my-layout
<template><view class="header">...</view><view class="body">...</view><view class="foot">...</view>
</template>
使用插槽
1)默认插槽
匿名插槽,直接在组件合适的位置用 <slot>
标签即可,声明插槽如下:
<template><view class="header"><slot></slot></view>...
</template>
使用时,直接在my-layout标签内部插入标签即可,填充插槽如下:
<my-layout><div>我来填充插槽了!!</div>
</my-layout>
匿名插槽可以在组件中定义多处,填充插槽时如果不指定插槽的名称(如下面的具名插槽),将会填充所有匿名插槽
2)具名插槽
有名字的插槽,通过<slot>
标签的 name 属性为插槽指定名字,声明插槽如下:
<template><view class="header"><slot name="header"></slot></view><view class="body"><slot name="body"></slot></view>...
</template>
第一个插槽名为header,第二个插槽名为body,在使用组件时,需要在 <template>
标签中使用 v-slot:插槽名
或 #插槽名
选择填充的插槽,如下:
<my-layout><!-- 选择名为header的插槽 --><template v-slot:header><div>头部</div></template><!-- 选择名为body的插槽 --><template #body><div>身体</div></template>
</my-layout>
3)条件插槽
即如果满足某些条件,才生成这个插槽。这里用 v-if
结合 $slots.插槽名
实现使用哪些插槽才生成哪些插槽
<template><view class="header" v-if="$slots.header"><slot name="header"></slot></view><view class="body" v-if="$slots.body"><slot name="body"></slot></view>
</template>
假如只是用名为body的插槽,那么$slots.header将不存在,头部插槽将不会生成,如:
<my-layout><template #body><div>身体</div></template>
</my-layout>
4)动态传递插槽名
只需要在传递插槽名用 []包裹js变量 即可,格式为:v-slot:[插槽名变量]
或 #[插槽名变量]
,如下:
<template><my-layout><template v-slot:[headerSlotName]><div>头部</div></template><template #[bodySlotName]><div>身体</div></template></my-layout>
</template>
<script setup>import { ref } from 'vue';
const headerSlotName = ref('header')const bodySlotName = ref('body')
</script>