Vue中的slot,slot-scope,v-slot

slot-插槽,是Vue提供的一种HTML模版,由子组件提供的一种暴露给父组件的可以传入自定义内容的出口。

slot 有匿名插槽,具名插槽,作用域插槽三种。

// 一个元素里只能有一个匿名插槽
<div class="child1">
     <!--匿名插槽-->
      <slot>匿名插槽按钮</slot>
</div>

// 一个元素可以有多个具名插槽
<div class="child2">
     <!--具名插槽-->
     <slot name="top"></slot>
     <slot name="center"></slot>
     <slot name="bottom"></slot>
</div>

// 作用域插槽:让插槽内容能够访问子组件中才有的数据,绑定在 <slot> 元素上的 attribute 被称为插槽 prop
<div class="child3">
      <slot name="top" :data="item"></slot>
</div>

<child3>
      <div slot="top" slot-scope="slotprop">{{slotprop.data}}</div>
 </child3>

在vue2.6及已上版本,slot 和slot-scope已经开始废弃, 有了新的替代: v-slot,v-slot只能用在template 上,和组件标签上。

// v-slot的具名插槽
<div class="child4">
      <slot name="top"></slot>
</div>
<child4 v-slot:top>
     <div>top</div>
</child4>
// v-slot的匿名插槽 <div class="child5"> <slot></slot> </div> <child5 v-slot> <div>top</div> </child5>
// v-slot的具名插槽的缩写 和不缩写 <child #top> <div>top</div> </child> <child v-slot:top> <div>top</div> </child>
// v-slot的作用域插槽 <div class="child4"> <slot name="top" :data="item"></slot> </div> <child4> <template #top="slotProps"> <div>{{slotProps.data}}</div> </template> </child4>
原文地址:https://www.cnblogs.com/jiajia123/p/12526307.html