Vue.js 插槽

插槽幫助您在組件中定位內容,並允許父組件對其進行排列。 一個組件可以完全負責生成其輸出,就像這個例子: Vue.component('user-name', { props: ['name'], template: '<p>Hi {{ name }}</p>' }) 或者它也可以讓父組件注入任何類型的內容,使用 插槽。 什麼是插槽?它是組件輸出中的一個保留空間,等待填充。 您可以通過將 <slot></slot> 放入組件模板中來定義一個插槽: Vue.component('user-information', { template: '<div class="user-information"><slot></slot></div>' }) 使用這個組件時,添加在開始和結束標籤之間的任何內容將添加到插槽佔位符中: <user-information> <h2>Hi!</h2> <user-name name="Flavio"></user-name> </user-information> 如果您將任何內容放置在 <slot></slot> 標籤中,則該內容將作為默認內容,以防沒有傳入內容。 一個復雜的組件布局可能需要更好的方式來組織內容,同時還有多個插槽。 這就是為什麼 Vue 為我們提供了 具名插槽。 具名插槽 使用具名插槽,您可以將插槽的各個部分分配給組件模板布局中的特定位置,並使用 slot 屬性為任何標籤分配內容。 任何位於模板標籤外部的內容都將添加到主要的 slot 中。 為方便起見,在此示例中,我在 page 單文件組件中使用了一個模板: <template> <div> <main> <slot></slot> </main> <aside> <slot name="sidebar"></slot> </aside> </div> </template> 這裡是如何在父組件中提供插槽內容: <page> <template v-slot:sidebar> <ul> <li>Home</li> <li>Contact</li> </ul> </template> <h2>Page title</h2> <p>Page content</p> </page> 還有一個方便的簡寫,即 #:...