插槽就是子組件預(yù)留給父組件放置內(nèi)容的空間,如果沒有插槽,那么我們在父組件中使用子組件時(shí),往子組件里添加內(nèi)容是無效的。
父組件:
<template>
<div style="text-align: center">
<todo-item>
<!-- 子組件標(biāo)簽里的內(nèi)容將不會(huì)顯示 -->
<span>這里是父組件DOM</span>
</todo-item>
</div>
</template>
那么有什么辦法可以讓子組件標(biāo)簽像div一樣可以在里面放置內(nèi)容嗎?當(dāng)然是有的,就是 我們要介紹的插槽slot。
slot
如果我們在子組件中添加插槽,那么放入子組件標(biāo)簽中的內(nèi)容就會(huì)被加載到slot中。
子組件:
<template>
<div style="text-align: center" class='child'>
<h3>這是子組件</h3>
<!-- 像這樣添加slot標(biāo)簽即可 -->
<slot></slot>
</div>
</template>
這樣父組件中添加的內(nèi)容將會(huì)替換掉slot,相當(dāng)于
子組件:
<div style="text-align: center" class='child'>
<h3>這是子組件</h3>
<!-- slot標(biāo)簽會(huì)被替換掉 -->
<span>這里是父組件DOM</span>
</div>
每一個(gè)子組件都應(yīng)該有一個(gè)像這樣不帶名字的插槽,稱為單個(gè)插槽。
同時(shí)我們也可以增加一些帶有名字的插槽,控制DOM內(nèi)容的不同位置,帶有name屬性的插槽稱為具名插槽。
子組件
<template>
<div style="text-align: center" class='child'>
<slot name="top"></slot>
<h3>這是子組件</h3>
<slot></slot>
<hr style="margin-top: 20px">
<slot name="down"></slot>
</div>
</template>
父組件中要添加slot屬性:
<template>
<div style="text-align: center">
<todo-item>
<span class="father-dom">這里是父組件DOM</span>
<span slot="down">這是底部</span>
<span slot="top">這是頂部</span>
</todo-item>
</div>
</template>
不管父組件中增加的DOM先后順序如何,具名插槽總是對應(yīng)到同名的子組件位置處,剩下的對應(yīng)到單個(gè)插槽處。如果在父組件中給了slot屬性,但是子組件中并沒有該插槽,那么那個(gè)標(biāo)簽將不會(huì)顯示。
slot-scope
這個(gè)屬性是給父組件中插入在子組件標(biāo)簽中的DOM使用的,可以獲取插槽上的屬性值。
父組件
<template>
<div style="text-align: center">
<todo-item :message="message">
<template slot-scope="scope">
<span>{{scope}}</span><br>
<span>{{scope.data}}</span>
</template>
</todo-item>
</div>
</template>
子組件:
<template>
<div style="text-align: center" class='child'>
<h3>這是子組件</h3>
<slot :data="message"></slot>
</div>
</template>
父組件中slot-scope綁定的scope對應(yīng)的數(shù)據(jù)就是子組件中slot上的data。