對vue中插槽(slot)的理解
阿新 • • 發佈:2020-09-11
單個插槽
單個插槽是vue的官方叫法,也可以叫它預設插槽,或者與具名插槽相對,也可以成為匿名插槽,因為它不用設定name屬性
單個插槽可以放在元件的任意位置,但一個元件最多有一個該類插槽。
例子:
<template> <div class="father"> <span>這裡是父元件</span> <child> <div> 父元件在子元件內新增的html片段 </div> </child> </div> </template>
<template>
<div class="child">
<span>這裡是子元件</span>
<slot></slot>
</div>
</template>
slot標籤將會被替換為父元件在該元件上新增的html片段。
具名插槽
具名插槽可以設定name屬性,這意味著一個元件內可以有多處插槽。
例子:
<template> <div class="father"> <span>這裡是父元件</span> <child> <div slot="slot1"> 父元件在子元件內新增的html片段 </div> <div slot="slot2"> 父元件在子元件內新增的html片段 </div> </child> </div> </template>
<template>
<div class="child">
<slot name="slot1"></slot>
<span>這裡是子元件</span>
<slot name="slot2"></slot>
</div>
</template>
這等效於:
<template> <div class="father"> <span>這裡是父元件</span> <child></child> </div> </template>
<template>
<div class="child">
<div slot="slot1">
父元件在子元件內新增的html片段
</div>
<span>這裡是子元件</span>
<div slot="slot2">
父元件在子元件內新增的html片段
</div>
</div>
</template>
作用域插槽
對比前面兩種插槽,我們可以叫它帶資料的插槽。
但是作用域插槽要求,在slot上面繫結資料。也就是你得寫成大概下面這個樣子。
<slot :data="data"></slot>
export default {
data: function(){
return {
data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
}
},
}
插槽最後顯示不顯示是看父元件有沒有在child下面寫模板,像下面那樣。
<child>
<div slot-scope="hht">{{hht.data}}</div>
</child>