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

fel*_*cst 13 javascript components vue.js vue-component vuejs2

我有一个列表和一个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>
Run Code Online (Sandbox Code Playgroud)

contact_list_item.vue

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

当我在特定组件中使用contact_list时,我希望能够发送一个插槽,将一些新列添加到contact_list_item组件中.此插槽将使用在contact_list_item组件内呈现的特定联系人的数据来生成新列.

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

提前致谢.

Ber*_*ert 9

插槽是最好的方法,您需要为contact-list-item组件使用范围插槽.我对pug并不熟悉,所以我将使用HTML作为示例.

contact-list您将添加一个插槽.请注意,在这种情况下,联系人将作为财产传递.这样我们就可以利用范围内的插槽.

<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>
Run Code Online (Sandbox Code Playgroud)

然后添加一个插槽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>
Run Code Online (Sandbox Code Playgroud)

最后,在Vue模板中,使用范围模板.

<div id="app">
  <contact-list :contacts="contacts">
    <template scope="{contact}">
      <div class="table-col">{{contact.id}}</div>
    </template>
  </contact-list>
</div>
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子.我不知道你的样式是什么,但请注意id列现在显示在contact-list-item.


DrS*_*sor 7

您可以用于template将插槽注册到子组件的子组件。

还有一种情况是您想要拥有许多命名槽。

孩子.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>
Run Code Online (Sandbox Code Playgroud)

孙子.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>
Run Code Online (Sandbox Code Playgroud)

父级.vue

<template>
  <div>
    <h2>Come to grandpa</h2>
    <child :babies="myGrandChilds">
      <button slot="myGrandChilds[2].name">baby cry</button>
    </child>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)