插槽就是子組件預留給父組件放置內容的空間,如果沒有插槽,那么我們在父組件中使用子組件時,往子組件里添加內容是無效的。
父組件:
<template>
<div style="text-align: center">
<todo-item>
<!-- 子組件標簽里的內容將不會顯示 -->
<span>這里是父組件DOM</span>
</todo-item>
</div>
</template>
那么有什么辦法可以讓子組件標簽像div一樣可以在里面放置內容嗎?當然是有的,就是 我們要介紹的插槽slot。
slot
如果我們在子組件中添加插槽,那么放入子組件標簽中的內容就會被加載到slot中。
子組件:
<template>
<div style="text-align: center" class='child'>
<h3>這是子組件</h3>
<!-- 像這樣添加slot標簽即可 -->
<slot></slot>
</div>
</template>
這樣父組件中添加的內容將會替換掉slot,相當于
子組件:
<div style="text-align: center" class='child'>
<h3>這是子組件</h3>
<!-- slot標簽會被替換掉 -->
<span>這里是父組件DOM</span>
</div>
每一個子組件都應該有一個像這樣不帶名字的插槽,稱為單個插槽。
同時我們也可以增加一些帶有名字的插槽,控制DOM內容的不同位置,帶有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先后順序如何,具名插槽總是對應到同名的子組件位置處,剩下的對應到單個插槽處。如果在父組件中給了slot屬性,但是子組件中并沒有該插槽,那么那個標簽將不會顯示。
slot-scope
這個屬性是給父組件中插入在子組件標簽中的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對應的數據就是子組件中slot上的data。