<template>
<div class="demo-alert-box">
<span>
<slot v-bind:user="user">{{user.lastname}}slot>
span>
<h3>
<slot name="titleSlot" v-bind:user="user">{{user.lastname}}slot>
h3>
div>
template>
<script>
export default {
data(){
return{
user:{
firstname:'tony',
lastname:'tommars'
}
}
}
}
script>
<h4 style="color:red">具名插槽h4>
<slot-box>
<template v-slot>
<div>具名插槽(default)div>
template>
<template v-slot:titleSlot>
<div>具名插槽(titleSlot)div>
template>
slot-box>

<h4 style="color:red">标准作用域插槽h4>
<slot-box>
<template v-slot:default="slotProps">
firstName:{{slotProps.user.firstname}}
<br>
lastName:{{slotProps.user.lastname}}
template>
slot-box>

<h4 style="color:red">标准作用域插槽,v-slot缩写h4>
<slot-box>
<template #default="slotProps">
firstName:{{slotProps.user.firstname}}
<br>
lastName:{{slotProps.user.lastname}}
template>
slot-box>
<h4 style="color:red">标准作用域插槽,v-slot缩写,解构插槽prop+重命名h4>
<slot-box>
<template #default={user:body}>
firstName:{{body.firstname}}
<br>
lastName:{{body.lastname}}
template>
slot-box>

<h4 style="color:red">独占默认插槽的写法(只有一个默认插槽)h4>
<slot-box v-slot:default="slotProps">
firstName:{{slotProps.user.firstname}}
<br>
lastName:{{slotProps.user.lastname}}
slot-box>

<h4 style="color:red">当出现多个插槽时,需要使用标准的templateh4>
<slot-box>
<template v-slot:default="slotProps">
firstName:{{slotProps.user.firstname}}
<br>
lastName:{{slotProps.user.lastname}}
template>
<template v-slot:titleSlot="otherslotProps">
firstName:{{otherslotProps.user.firstname}}
<br>
lastName:{{otherslotProps.user.lastname}}
template>
slot-box>

说明
使用[],可以传入参数,动态的变化插槽名,达到动态使用不同插槽的效果
代码示例
比如外部只定义了一个插槽内容,但是需要动态的将内容显示到不同插槽上,可以使用这个动态参数
<h4 style="color:red">独占默认插槽的写法(只有一个插槽)h4>
<button @click="testDynamicParam">测试动态参数button>
<slot-box v-slot:[slotDynamicParam]="slotProps">
firstName:{{slotProps.user.firstname}}
<br>
lastName:{{slotProps.user.lastname}}
slot-box>
testDynamicParam(){
if(this.slotparamChange){
this.slotDynamicParam='titleSlot'
}else{
this.slotDynamicParam='default'
}
this.slotparamChange=!this.slotparamChange
},
效果


前者是将默认插槽进行了内容重新定义,命名的titleSlot插槽使用的默认内容,但是点击按钮后,变成了对命名的titleSlot插槽内容重新定义,默认插槽变成了默认内容