VueJS - Pass slot to child of child component

Viewed 22616

I have a list and a list_item component that I reuse a lot inside my application. On a simplified form:

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>

When I use contact_list inside a specific component, I want to be able to send a slot that will add some new columns to the contact_list_item component. This slot will use data of the specific contact that is being rendered inside that contact_list_item component to generate the new columns.

How could I achieve that? Is using slot the best approach?

Thanks in advance.

4 Answers

You can use template for registering slot to the child of child component.

There is also a case when you want to have many named slots.

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>

Add to @DrSensor's answer.

In Vue3, you should use dynamic slot name.

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

To translate several slots one level down conveniently to use the method described at this link, and if you modify it a little, perhaps you will be able to transfer it deeper.

Related