大家一看代码就知道插槽用在什么地方了。
简单说就是父组件在引用子组件时,里面填写的内容,可以填充到子组件的<slot></slot>里面。
默认插槽
src/components/MyBtn.vue:
<template>
<button class="solid-button red-button">
<slot>默认内容</slot>
</button>
</template>
<script lang='ts' setup name='MyBtn'>
</script>
<style scoped>
.solid-button {
display: inline-block;
padding: 10px 20px;
font-size: 16px;
color: white;
text-align: center;
text-decoration: none;
border-radius: 5px;
border: none;
cursor: pointer;
}
.red-button {
background-color: red;
}
</style>src/slot/SlotFather.vue:
<template>
<div class="slotFather">
<h1>默认插槽</h1>
<MyBtn>提交</MyBtn>
<MyBtn>保存</MyBtn>
<MyBtn>
<span style="color: blue;">确认</span>
<br />
<button>测试</button>
</MyBtn>
<MyBtn />
</div>
</template>
<script lang='ts' setup name='SlotFather'>
import MyBtn from '@/components/MyBtn.vue';
</script>
<style scoped>
.slotFather {
background-color: moccasin;
color: black;
}具名插槽
MyBtn2.vue:
<template>
<div>
<slot name="beforeBtn"></slot>
</div>
<button class="gradient-button">
<slot name="btnText">默认内容</slot>
</button>
</template>
<script lang='ts' setup name='MyBtn2'>
</script>
<style scoped>
.gradient-button {
display: inline-block;
padding: 10px 20px;
font-size: 16px;
color: white;
text-align: center;
text-decoration: none;
border-radius: 5px;
border: none;
cursor: pointer;
background: linear-gradient(to right, green, darkgreen);
}
</style>SlotFather.vue:
<h1>具名插槽</h1>
<MyBtn2>
<template #beforeBtn>
<span style="color: red;">前置内容</span>
</template>
<template #btnText>提交</template>
</MyBtn2>说明:
跟上面的默认插槽结合看,代码很明晰了,不解释了。
其实写法应该是<template v-slot:beforeBtn>,但是可以简写<template #beforeBtn>
条件插槽
有时候可以根据插槽是否存在来决定是否渲染内容,例如上面的beforeBtn,如果父组件不传相应内容,就不渲染。
MyBtn2.vue:
<template>
<div v-if="$slots.beforeBtn">
<slot name="beforeBtn"></slot>
</div>
<button class="gradient-button">
<slot name="btnText">默认内容</slot>
</button>
</template>SlotFather.vue:
<h1>条件插槽</h1>
<MyBtn2>
<template #btnText>保存</template>
</MyBtn2> 