2017-07-03 45 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>