javascriptvue.jsvuejs3quasar-frameworkvuejs-slots

can not loop through $slots object in Vue 3 to pass all slots from parent to child


I can not loop through the $slots object in Vue 3 to pass all slots from parent to child, the $slots object seems empty in the child component.

How can I loop through the $slots object to pass all parent slots to the child component?

I get this error when I run the code: TypeError: Cannot read properties of null (reading 'key')

TypeError: Cannot read properties of null (reading 'key')

Here is a sandbox about my problem and you can uncomment line 5 to see the complete result: https://codesandbox.io/s/blazing-bush-g7c9h?file=/src/pages/Index.vue

GitHub sample: https://github.com/firibz/vue3slots

parent:

<system-input filled v-model="text" label="input">
  <template v-slot:before>
    <q-icon name="mail" />
  </template>
</system-input>

child:

  <div class="row justify-center">
    <q-input v-model="componentValue" v-bind="$attrs" style="width: 250px">
      <template v-for="(_, slot) of $slots" v-slot:[slot]="scope">
        <slot :name="slot" v-bind="scope"/>
      </template>
    </q-input>
    <q-separator class="full-width" color="secondary" />
    <div class="bg-negative full-width q-pa-lg">slots: {{ $slots }}</div>
    <div class="bg-warning full-width q-pa-lg">slots: {{ $slots.before }}</div>
  </div>

Solution

  • You have to use Object.keys($slots) in order to use slots on v-for.

    <q-input v-model="componentValue" v-bind="$attrs" style="width: 250px">
      <template v-for="(slot, index) of Object.keys($slots)" :key="index" v-slot:[slot]>
        <slot :name="slot"></slot>
      </template>
    </q-input>