VueJS - 将插槽传递给子组件的子节点

时间:2017-07-03 14:35:03

标签: javascript vue.js components vuejs2 vue-component

我有一个列表和一个list_item组件,我在我的应用程序中重复使用了很多。在简化表格上:

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组件内呈现的特定联系人的数据来生成新列。

我怎么能实现这一目标?使用插槽是最好的方法吗?

提前致谢。

2 个答案:

答案 0 :(得分:7)

插槽是最好的方法,您需要为contact-list-item组件使用范围内的插槽。我对pug并不熟悉,所以我将使用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

答案 1 :(得分:1)

您可以使用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>
相关问题