插槽
在子組件中,添加<slot></slot>標(biāo)簽,然后在父組件中使用該子組件時(shí),就可以動(dòng)態(tài)的添加內(nèi)容。
插槽是可以指定默認(rèn)內(nèi)容的,使用組件時(shí),有填充內(nèi)容,填充內(nèi)容會(huì)把默認(rèn)內(nèi)容覆蓋;否則顯示插槽默認(rèn)內(nèi)容。
//子組件 son
<template>
<div>
<div>1111</div>
<slot>我是插槽的默認(rèn)內(nèi)容</slot>
</div>
</template>
//父組件(記得先引入子組件)
<template>
<div>
//使用子組件
<son>
<div>我是填充內(nèi)容,會(huì)把插槽中的默認(rèn)內(nèi)容覆蓋</div>
</son>
</div>
</template>
匿名插槽
一個(gè)組件中可以有多個(gè)匿名插槽,在父組件使用這個(gè)組件時(shí),有幾個(gè)匿名插槽,填充內(nèi)容就會(huì)被拷貝幾份。
注意:在一個(gè)組件內(nèi),推薦只使用一個(gè)匿名插槽,其他使用具名插槽。
具名插槽
相當(dāng)于匿名插槽有了名字:<slot name="插槽名">默認(rèn)內(nèi)容</slot>。
在父組件使用子組件填充內(nèi)容時(shí),給填充插槽的標(biāo)簽增加slot屬性,并指定對(duì)應(yīng)的插槽名:<div slot="插槽名">填充內(nèi)容</div>
Vue中v-slot指令
在使用插槽填充內(nèi)容時(shí),利用v-slot指令替換slot屬性。
注意:v-slot指令只能使用在<template>標(biāo)簽上
v-slot指令簡(jiǎn)寫#
//匿名插槽的名字默認(rèn)default
<son>
<template v-slot:插槽名>
<div>這個(gè)內(nèi)容會(huì)填充到該插槽對(duì)應(yīng)的位置</div>
</template>
</slot>
作用域插槽
作用域插槽也就是帶數(shù)據(jù)的插槽,讓父組件在填充子組件的插槽時(shí)也能使用子組件中的數(shù)據(jù)。
使用場(chǎng)景:子組件提供數(shù)據(jù),父組件決定如何渲染時(shí)使用。
//子組件 son
<template>
<div>
//1、子組件通過v-bind:數(shù)據(jù)名稱="數(shù)據(jù)名稱"方式來暴露數(shù)據(jù)
<slot v-bind:names="names">插槽默認(rèn)內(nèi)容</slot>
</div>
</template>
//父組件(記得先引入子組件)
<template>
<div>
//使用子組件
<son>
//2、父組件在<template slot-scope="作用域名稱">上接收數(shù)據(jù)
<template slot-scope="abc">
//3、父組件通過 作用域名稱.數(shù)據(jù)名稱 來使用數(shù)據(jù)
<div>我是填充內(nèi)容{{abc.names}}</div>
</template>
</son>
</div>
</template>
注意:
slot-scope="abc"可用v-slot指令替換,
即:v-slot:default="abc"或者#default="abc"
文章原有字?jǐn)?shù)不喜歡,隨便加句話吧,嘿嘿_