插槽(Slot)
定義一個(gè)名child子組件,為該子組件添加內(nèi)容應(yīng)該在子組件的template中定義,直接在父組件的<child>標(biāo)簽中定義的內(nèi)容不會(huì)被渲染。
在子組件中通過(guò)加入<slot>元素占位,便能夠渲染父組件中子組件標(biāo)簽中的內(nèi)容了。
插槽內(nèi)容
插槽可以有默認(rèn)內(nèi)容,當(dāng)在父組件中沒(méi)有提供內(nèi)容的時(shí)候,來(lái)進(jìn)行顯示。
<!-- submit-button --><button type="submit"> <slot>Submit</slot></button>1.<submit-button></submit-button>⬇️ <button type="submit"> Submit</button>2.<submit-button> Save</submit-button>⬇️<button type="submit"> Save</button>
作用域
父級(jí)模板里的所有內(nèi)容都是在父級(jí)作用域中編譯的;子模板里的所有內(nèi)容都是在子作用域中編譯的。
具名插槽
試想,我們有一個(gè)帶有如下模版的<base-layout>組件
<div class="container"> <header> <!-- 我們希望把頁(yè)頭放這里 --> </header> <main> <!-- 我們希望把主要內(nèi)容放這里 --> </main> <footer> <!-- 我們希望把頁(yè)腳放這里 --> </footer></div>
可以看到,在組件中顯示的內(nèi)容是劃分不同的部位的,這個(gè)時(shí)候就需要使用到<slot>元素的一個(gè)特有的屬性:name來(lái)實(shí)現(xiàn)了。這個(gè)特性可以用來(lái)定義額外的插槽。
<div class="container"> <header> <slot name="header"></slot> </header> <main> <slot></slot> </main> <footer> <slot name="footer"></slot> </footer></div>
一個(gè)不帶 name 的 <slot> 出口會(huì)帶有隱含的名字“default”。
在向具名插槽提供內(nèi)容的時(shí)候,我們可以在一個(gè) <template> 元素上使用 v-slot 指令,并以 v-slot 的參數(shù)的形式提供其名稱:
<base-layout> <template v-slot:header> <h1>Here might be a page title</h1> </template> <p>A paragraph for the main content.</p> <p>And another one.</p> <template v-slot:footer> <p>Here's some contact info</p> </template></base-layout>
現(xiàn)在 <template> 元素中的所有內(nèi)容都將會(huì)被傳入相應(yīng)的插槽。任何沒(méi)有被包裹在帶有 v-slot 的 <template> 中的內(nèi)容都會(huì)被視為默認(rèn)插槽的內(nèi)容。
當(dāng)然,也可以將默認(rèn)插槽的內(nèi)容通過(guò)v-slot:default包裹起來(lái)。
v-slot 只能添加在一個(gè) <template> 上
作用域插槽
當(dāng)我們希望能夠讓插槽內(nèi)容能夠訪問(wèn)子組件中才有的數(shù)據(jù)時(shí),我們可以將數(shù)據(jù)作為一個(gè)<slot>元素的特性綁定上去
新聞熱點(diǎn)
疑難解答
圖片精選