无法循环遍历 Vue 3 中的 $slots 对象以将所有插槽从父级传递到子级

2024-01-08

我无法循环遍历 Vue 3 中的 $slots 对象以将所有插槽从父组件传递到子组件,$slots 对象在子组件中似乎为空。

如何循环遍历 $slots 对象以将所有父插槽传递给子组件?

当我运行代码时出现此错误: 类型错误:无法读取 null 的属性(读取“key”)

这是一个关于我的问题的沙箱,您可以取消注释第 5 行以查看完整的结果:https://codesandbox.io/s/blazing-bush-g7c9h?file=/src/pages/Index.vue https://codesandbox.io/s/blazing-bush-g7c9h?file=/src/pages/Index.vue

GitHub 示例:https://github.com/firibz/vue3slots 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>

您必须使用 Object.keys($slots) 才能在 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法循环遍历 Vue 3 中的 $slots 对象以将所有插槽从父级传递到子级 的相关文章

随机推荐