插槽 (slot)
為什么使用 slot
- 插槽的目的是讓我們原來的設(shè)備具備更多的擴展性
- 比如電腦的 USB 插槽, 可以擴展 U 盤瘸味、硬盤谦纱、手機、音響橡娄、鍵盤捺氢、鼠標(biāo)等
組件的插槽
-
組件的插槽也是為了讓我們封裝的組件更加具有擴展性
- 讓使用者可以決定組件內(nèi)部的一些內(nèi)容到底展示什么
-
例如:
- 移動開發(fā)中, 幾乎每個頁面都有導(dǎo)航欄
- 導(dǎo)航欄我們必然會封裝成一個插件, 比如 nav-bar 組件
- 一旦有了這個組件, 我們就可以在多個頁面中復(fù)用了
如何封裝組件? (slot)
原則: 抽取共性, 保留不同
最好的封裝方法就是將共性抽取到組件中, 將不同暴露為插槽
一旦我們預(yù)留了插槽, 就可以讓使用者根據(jù)自己的需求, 決定插槽中插入什么內(nèi)容
是搜索框, 還是文字, 菜單, 都由調(diào)用者自己來決定
插槽的使用
插槽的基本使用
- 在組件模板中使用 slot 標(biāo)簽
<!-- 子組件 -->
<template>
<slot></slot>
</template>
即可設(shè)置一個插槽
然后在使用組件時, 往組件標(biāo)簽內(nèi)部填如入相應(yīng)的代碼即可
<!-- 父組件 -->
<template>
<div id="app">
<child>
<p>插槽實例</p>
</child>
</div>
</template>
-
注意:
- 在組件模版實例中, 無論寫多少代碼, 都會同時放入到組件中進行替換, 一起生效
插槽的默認(rèn)值
- 在 slot 標(biāo)簽中填入的任何代碼, 都會被當(dāng)作默認(rèn)值
- 如果在組件實例中沒有為插槽添加代碼, 那么插槽的默認(rèn)值將生效
- 反之, 插槽的默認(rèn)值被覆蓋
<slot>
<p>我是默認(rèn)值</p>
</slot>
具名插槽
可以發(fā)現(xiàn), 如果在子組件模板中有多個插槽 slot , 那么我們在使用插槽時, 會把所有 slot 的值都替換掉
所以, 當(dāng)我們想單獨修改某一個 slot 時, 可以使用具名插槽
-
使用步驟
- 為插槽添加一個 name 屬性
- 使用時通過 slot=name 的形式綁定對應(yīng)的插槽
父組件 template 模板
<template>
<div id="app">
<cpn>
<span slot="center">中間插槽</span>
<button slot="left">左邊插槽</button>
</cpn>
</div>
</template>
子組件 template 模板
<template id="cpn">
<div>
<slot name="left"><span>left</span></slot>
<slot name="center"><span>center</span></slot>
<slot name="right"><span>right</span></slot>
</div>
</template>
編譯作用域
父組件模版的所有東西都會在父組件的作用域內(nèi)編譯
子組件模板的所有東西都會在子組件的作用域內(nèi)編譯
即在父組件的模板實例中使用的屬性都是來自父組件的實例對象
子組件的模板實例中使用的屬性來自子組件的實例對象
作用域插槽
- 父組件替換插槽的標(biāo)簽, 但是屬性蝗拿、變量由子組件來提供
- 即在父組件模板實例中, 如何使用子組件的數(shù)據(jù)
<!-- 子組件 -->
<template>
<div>
<slot :data="pLanguage">
<ul>
<li v-for="item in pLanguage">{{item}}</li>
</ul>
</slot>
</div>
</template>
首先, 我們需要在插槽標(biāo)簽添加一個屬性(該屬性名任意)
然后, 我們需要在父組件模版實例中獲得數(shù)據(jù)
<!-- 父組件 -->
<template>
<div id="app">
<child></child>
<child>
<!-- 在vue2.5x之前需要使用template來獲得數(shù)據(jù), 2.5x之后任何標(biāo)簽都可以 -->
<template slot-scope="slot">
<span v-for="item in slot.data">{{item}}</span>
</template>
</child>
<child></child>
</div>
</template>
- slot-scope 屬性獲得由插槽傳來的數(shù)據(jù)對象