2017-07-03 82 views
4

我有一個list和一個list_item組件,我可以在我的應用程序中重複使用很多。在一個簡單的形式:VueJS - 將子槽傳給子組件

contact_list.vue

<template lang="pug"> 
    .table 
     .table-header.table-row 
     .table-col Contact 
     .table-col Info 

     .table-body 
      contact-list-item(v-for='contact in contacts', 
          :contact='contact', 
          @click='doSomething()') 

</template> 

contact_list_item.vue

<template lang="pug"> 
.table-row(@click='emitClickEvent') 
    .table-col {{ contact.name }} 
    .table-col {{ contact.info }} 
</template> 

當我使用CONTACT_LIST一個特定組成部分中,我希望能夠發送該插槽將向contact_list_item組件添加一些新列。此插槽將使用該contact_list_item組件內正在呈現的特定聯繫人的數據來生成新列。

我怎麼能做到這一點?使用插槽是最好的方法?

在此先感謝。

回答

3

插槽是最好的方法,您將需要使用contact-list-item組件的範圍插槽。我對帕格不是很熟悉,所以我將使用HTML作爲示例。

contact-list您將添加一個插槽。注意在這種情況下,該聯繫人作爲財產傳遞。這是我們可以利用scoped slots

<div class="table"> 
    <div class="table-header table-row"> 
    <div class="table-col">Contact</div> 
    <div class="table-col">Info</div> 
    </div> 
    <div class="table-body"> 
    <contact-list-item v-for='contact in contacts' 
         :contact="contact" 
         @click="doSomething" 
         :key="contact.id"> 
     <slot :contact="contact"></slot> 
    </contact-list-item> 
    </div> 
</div> 

然後給contact-list-item添加一個插槽。

<div class="table-row" @click="emitClickEvent"> 
    <div class="table-col">{{contact.name}}</div> 
    <div class="table-col">{{contact.info}}</div> 
    <slot></slot> 
</div> 

最後,在你的Vue模板中,使用作用域模板。

<div id="app"> 
    <contact-list :contacts="contacts"> 
    <template scope="{contact}"> 
     <div class="table-col">{{contact.id}}</div> 
    </template> 
    </contact-list> 
</div> 

這是working example。我不知道你的款式是什麼,但注意id列現在顯示在contact-list-item

0

您可以使用template將插槽註冊到子組件的子項。

也有一種情況,當你想有很多命名插槽。

child.vue

<template> 
    <div> 
    <h2>I'm a father now</h2> 
    <grandchild :babies="babies"> 
     <template v-for="(baby, id) in babies" :slot="baby.name"> 
     <slot :name="baby.name"/> 
     </template> 
    </grandchild> 
    </div> 
</template> 

grandchild.vue

<template> 
    <div> 
    <p v-for="(baby, id) in babies" :key="id"> 
     <span v-if="baby.isCry">Owe...owe...</span> 
     <slot :name="baby.name"> 
    </p> 
    </div> 
</template> 

parent.vue

<template> 
    <div> 
    <h2>Come to grandpa</h2> 
    <child :babies="myGrandChilds"> 
     <button slot="myGrandChilds[2].name">baby cry</button> 
    </child> 
    </div> 
</template>