slot基本使用
在子組件中,使用特殊的元素<slot>就可以為子組件開啟一個插槽。
該插槽插入什么內(nèi)容取決于父組件如何使用。
我們通過一個簡單的例子,來給子組件定義一個插槽:
<slot>中的內(nèi)容表示,如果沒有在該組件中插入任何其他內(nèi)容,就默認(rèn)顯示該內(nèi)容
有了這個插槽后,父組件如何使用呢?

具名插槽slot
當(dāng)子組件的功能復(fù)雜時,子組件的插槽可能并非是一個。
比如我們封裝一個導(dǎo)航欄的子組件,可能就需要三個插槽,分別代表左邊、中間、右邊。
那么,外面在給插槽插入內(nèi)容時,如何區(qū)分插入的是哪一個呢?
這個時候,我們就需要給插槽起一個名字
如何使用具名插槽呢?
非常簡單,只要給slot元素一個name屬性即可
<slot name='myslot'></slot>
我們來給出一個案例:

作用域插槽:
我們先提一個需求:
子組件中包括一組數(shù)據(jù),比如:pLanguages: [‘JavaScript’, ‘Python’, ‘Swift’, ‘Go’, ‘C++’]
需要在多個界面進(jìn)行展示:
某些界面是以水平方向一一展示的,
某些界面是以列表形式展示的,
某些界面直接展示一個數(shù)組
內(nèi)容在子組件,希望父組件告訴我們?nèi)绾握故?,怎么辦呢?
利用slot作用域插槽就可以了
我們來看看子組件的定義:

作用域插槽:使用
在父組件使用我們的子組件時,從子組件中拿到數(shù)據(jù):
我們通過<template slot-scope="slotProps">獲取到slotProps屬性
在通過slotProps.data就可以獲取到剛才我們傳入的data了

v-slot
在 2.6.0 中,我們?yōu)榫呙宀酆妥饔糜虿宀垡肓艘粋€新的統(tǒng)一的語法 (即 v-slot 指令)。它取代了 slot 和 slot-scope 這兩個目前已被廢棄但未被移除且仍在文檔中的 attribute。新語法的由來可查閱這份 RFC。---vue.js官網(wǎng)
v-slot具名插槽使用
子組件中
<slot name="left">我是一個插槽默認(rèn)內(nèi)容</slot>
<slot name="center">我是二個插槽默認(rèn)內(nèi)容</slot>
<slot name="right">我是三個插槽默認(rèn)內(nèi)容</slot>
<slot>我是四個插槽默認(rèn)內(nèi)容</slot>
父組件使用
插槽的名字現(xiàn)在通過 v-slot:slotName 這種形式來使用
<template v-slot:left>
<p>111</p>
</template>
<template v-slot:center>
<p>222</p>
</template>
<template v-slot:right>
<p>333</p>
</template>
<template>
<p>444</p>
</template>
注意
沒有名字的 <slot> 隱含有一個 "default" 名稱
v-slot 只能添加到 <template> 或自定義組件上,這點與棄用的 slot 屬性不同
v-slot作用域插槽
子組件
<slot name="left">我是一個插槽默認(rèn)內(nèi)容</slot>
<slot name="center">我是二個插槽默認(rèn)內(nèi)容</slot>
<slot name="right" :data="sss">我是三個插槽默認(rèn)內(nèi)容 </slot>
<slot>我是四個插槽默認(rèn)內(nèi)容</slot>
<script>
export default {
data () {
return {
sss:['111','222','333','444']
}
}
}
</script>
父組件使用
<template v-slot:left>
<p>111</p>
</template>
<template v-slot:center>
<p>222</p>
</template>
<template v-slot:right="data1">
<ul>
<li v-for="(item,index) in data1.data " :key="index">
{{item}}
</li>
</ul>
</template>
<template>
<p>444</p>
</template>
效果展示
