Vue.js 插槽
插槽幫助您在組件中定位內容,並允許父組件對其進行排列。
一個組件可以完全負責生成其輸出,就像這個例子:
1 2 3 4
| Vue.component('user-name', { props: ['name'], template: '<p>Hi {{ name }}</p>' })
|
或者它也可以讓父組件注入任何類型的內容,使用 插槽。
什麼是插槽?它是組件輸出中的一個保留空間,等待填充。
您可以通過將 <slot></slot> 放入組件模板中來定義一個插槽:
1 2 3
| Vue.component('user-information', { template: '<div class="user-information"><slot></slot></div>' })
|
使用這個組件時,添加在開始和結束標籤之間的任何內容將添加到插槽佔位符中:
1 2 3 4
| <user-information> <h2>Hi!</h2> <user-name name="Flavio"></user-name> </user-information>
|
如果您將任何內容放置在 <slot></slot> 標籤中,則該內容將作為默認內容,以防沒有傳入內容。
一個復雜的組件布局可能需要更好的方式來組織內容,同時還有多個插槽。
這就是為什麼 Vue 為我們提供了 具名插槽。
具名插槽
使用具名插槽,您可以將插槽的各個部分分配給組件模板布局中的特定位置,並使用 slot 屬性為任何標籤分配內容。
任何位於模板標籤外部的內容都將添加到主要的 slot 中。
為方便起見,在此示例中,我在 page 單文件組件中使用了一個模板:
1 2 3 4 5 6 7 8 9 10
| <template> <div> <main> <slot></slot> </main> <aside> <slot name="sidebar"></slot> </aside> </div> </template>
|
這裡是如何在父組件中提供插槽內容:
1 2 3 4 5 6 7 8 9 10 11
| <page> <template v-slot:sidebar> <ul> <li>Home</li> <li>Contact</li> </ul> </template>
<h2>Page title</h2> <p>Page content</p> </page>
|
還有一個方便的簡寫,即 #:
1 2 3 4 5 6 7 8 9 10 11
| <page> <template #sidebar> <ul> <li>Home</li> <li>Contact</li> </ul> </template>
<h2>Page title</h2> <p>Page content</p> </page>
|
注意:Vue 2.6 中已將 slot 屬性棄用,改用 v-slot,並要求將其添加到 template 標籤中(而 slot 可以應用於任何標籤)
作用域插槽
在插槽中,我們無法從父組件中訪問子組件中包含的數據。
Vue 識別到這種使用場景並為我們提供了一種方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <template> <div> <main> <slot v-bind:dogName="dogName"></slot> </main> </div> </template>
<script> export default { name: 'Page', data: function() { return { dogName: 'Roger' } } } </script>
|
在父組件中,可以使用以下方式訪問我們傳遞的狗名稱:
1 2 3 4 5
| <page> <template v-slot="slotProps"> {{ slotProps.dogName }} </template> </page>
|
slotProps 只是一個變量,我們用它來訪問傳遞的 props。您也可以通過即時解構對象來避免設置變量來保存傳遞給子組件的 props:
1 2 3 4 5
| <page> <template v-slot="{ dogName }"> {{ dogName }} </template> </page>
|
tags: [“Vue.js”, “插槽”, “具名插槽”, “作用域插槽”]