插槽(slot):是組件的一塊HTML模板,父組件決定這塊模板顯不顯示以及怎麼顯示。html
位置由子組件自身決定(slot如今組件template的什麼位置,父組件傳過來的模板未來就顯示在什麼位置)flex
匿名插槽:只能有一個,能夠放在組件的任何位置spa
<div class="father"> //在父組件在裏面寫了html模塊 <son> //子組件的匿名插槽被下面的div模板使用了 <div> <span>菜單1</span> </div> </son> </div> <template> <div class="son"> <slot></slot> </div> </template>
具名插槽:有name屬性 能夠在一個組件中屢次出現,出如今不一樣的位置。code
父組件: <template> <div class="father"> <h3>這裏是父組件</h3> <child> <div class="tmpl" slot="up"> <span>菜單1</span> <span>菜單2</span> <span>菜單3</span> <span>菜單4</span> <span>菜單5</span> <span>菜單6</span> </div> <div class="tmpl" slot="down"> <span>菜單-1</span> <span>菜單-2</span> <span>菜單-3</span> <span>菜單-4</span> <span>菜單-5</span> <span>菜單-6</span> </div>
//沒有slot屬性的html模板默認關聯匿名插槽 <div class="tmpl"> <span>菜單->1</span> <span>菜單->2</span> <span>菜單->3</span> <span>菜單->4</span> <span>菜單->5</span> <span>菜單->6</span> </div> </child> </div> </template>
子組件:
<template> <div class="child"> // 具名插槽 <slot name="up"></slot> <h3>這裏是子組件</h3> // 具名插槽 <slot name="down"></slot> // 匿名插槽 <slot></slot> </div> </template>
做用域插槽(帶數據插槽):在slot上面綁定數據(匿名插槽和具名插槽的的樣式和內容都由父組件提供的模板決定)xml
父組件: <template> <div class="father"> <h3>這裏是父組件</h3> <!--第一次使用:用flex展現數據--> <child> <template slot-scope="user"> <div class="tmpl"> <span v-for="item in user.data">{{item}}</span> </div> </template> </child> <!--第二次使用:用列表展現數據--> <child> <template slot-scope="user"> <ul> <li v-for="item in user.data">{{item}}</li> </ul> </template> </child> <!--第三次使用:直接顯示數據--> <child> <template slot-scope="user"> {{user.data}} </template> </child> <!--第四次使用:不使用其提供的數據, 做用域插槽退變成匿名插槽--> <child> 我就是模板 </child> </div> </template>
子組件:
<template>
<div class="child">htm
<h3>這裏是子組件</h3>
// 做用域插槽
<slot :data="data"></slot>
</div>
</template>blog
export default {
data: function(){
return {
data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
}
}
}作用域