如何使用 Vue 命名插槽創(chuàng)建多個(gè)模板插槽?
Vue 插槽允許將父組件中的內(nèi)容注入到子組件中。
這是最基本的示例,如果我們不提供父級(jí)的任何slot 內(nèi)容,則我們將放在其中的任何內(nèi)容都會(huì)作為后備內(nèi)容。
- // ChildComponent.vue
- <template>
- <div>
- <slot> 后備內(nèi)容 </slot>
- </div>
- </template>
你組件代碼:
- // ParentComponent.vue
- <template>
- <child-component>
- 替換 slot 的默認(rèn)內(nèi)容
- </child-component>
- </template>
編譯后,我們的 DOM 將如下所示
- <div> 替換 slot 的默認(rèn)內(nèi)容 </div>
我們還可以將父組作用域內(nèi)的任何數(shù)據(jù)寫(xiě)在 slot 區(qū)域中。例如,父組件有一個(gè)名為title的數(shù)據(jù)字段,我們可以使用以下代碼將其注入到子組件中:
- // ParentComponent.vue
- <template>
- <child-component>
- {{ title }}
- </child-component>
- </template>
- <script>
- export default {
- data () {
- return {
- title: '這會(huì)傳遞給子組件',
- }
- }
- }
- </script>
為什么我們需要命名插槽
在Vue中使用命名插槽有兩個(gè)步驟:
- 使用name屬性從子組件中命名 slot
- 使用v-slot指令從父組件向這些命名插槽提供內(nèi)容
默認(rèn)情況下,不給插槽顯式的name屬性時(shí),它有默認(rèn)名字是default。
為了給我們的 slot 起個(gè)名字,元素具有一個(gè)特殊的name屬性,可以讓我們?cè)诙鄠€(gè)插槽之間進(jìn)行區(qū)分。
在下面的Article.vue 中,我們命名三個(gè) slot
- // Article.vue - Child Component
- <template>
- <div>
- <slot name="title"> 默認(rèn) title </slot>
- <slot name="content"> 默認(rèn) content </slot>
- <slot name="comments"> 默認(rèn) comments</slot>
- </div>
- </template>
然后,在父組件中,我們可以在元素上使用v-slot指令指定我們想要注入內(nèi)容的slot。
- // ParentComponent.vue
- <template>
- <div>
- <child-component>
- <template> 我的 Title </template>
- <template> 我的 Content </template>
- <template> 我的 Comments </template>
- </child-component>
- </div>
- </template>
因?yàn)檫@是沒(méi)有指定 slot 的名稱,所以顯示的是 slot 默認(rèn)的內(nèi)容。
要解決這個(gè)問(wèn)題,可以使用v-slot,指定的名稱要確保名稱與我們?cè)谧咏M件中聲明的名稱完全匹配。
- <template>
- <div>
- <child-component>
- <template v-slot:title> 我的 title </template>
- <template v-slot:content> 我的 content </template>
- <template v-slot:comments> 我的 comments </template>
- </child-component>
- </div>
- </template>
再次運(yùn)行:
使用 Vue 命名插槽有什么意義
命名槽讓我們可以使用多個(gè)槽,但是為什么這對(duì)我們Vue開(kāi)發(fā)人員有用呢。
簡(jiǎn)而言之,它使我們可以更好地組織開(kāi)發(fā)代碼,還可以編寫(xiě)更具擴(kuò)展性的代碼。
就個(gè)人而言,我認(rèn)為最重要的是,它允許我們?cè)诖a上使用插槽,從而使樣式設(shè)計(jì)變得更加容易。在我們的示例中,Article.vue子組件只有三個(gè)插槽,但是在實(shí)際應(yīng)用中,這些插槽看起來(lái)更像這樣,以便我們的組件可以向每個(gè)部分添加CSS樣式。
- <template>
- <div>
- <div class="title">
- <h1>
- <slot name="title"> 默認(rèn) Title </slot>
- </h1>
- </div>
- <div class="content">
- <p>
- <slot name="content"> 默認(rèn) Content </slot>
- </p>
- </div>
- <div class="comments">
- <slot name="comments"> 默認(rèn) Comments </slot>
- </div>
- </div>
- </template>
在此示例中,更容易理解為什么我們需要多個(gè) slot。由于我們注入的內(nèi)容是通過(guò)不同的<div>,<p>和DOM元素彼此分隔的。無(wú)法在一個(gè)slot中傳遞所有這些信息。
如果檢查DOM,可以看到使用v-slot的模板將內(nèi)容正確地插入到正確的位置。
~完,我是刷碗智,去刷碗了,下期見(jiàn)!
作者:Matt Maribojoc 譯者:前端小智 來(lái)源:stackabuse
原文:https://learn.co/2021/04/using-vue-named-slots-to-create-multile-template-slots/
本文轉(zhuǎn)載自微信公眾號(hào)「大遷世界」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系大遷世界公眾號(hào)。