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>