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

新手上路,请多包涵

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

联系人列表.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>

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

我怎样才能做到这一点?使用插槽是最好的方法吗?

提前致谢。

原文由 felipeecst 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 551
2 个回答

插槽是最好的方法,您将需要为 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 模板中,使用 scoped 模板。

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

这是一个 工作示例。我不知道您的样式是什么,但请注意 id 列现在显示在 contact-list-item 中。

原文由 Bert 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 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>

孙子.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>

父视图

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

原文由 DrSensor 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题