无法通过 Vue 3 中的 $slots 对象循环将所有插槽从父级传递给子级

问题描述 投票:0回答:4

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

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

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

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

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

GitHub 示例: https://github.com/firibz/vue3slots

家长:

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

孩子:

  <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>
javascript vue.js vuejs3 quasar-framework vuejs-slots
4个回答
12
投票

您必须使用 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>

2
投票

为了防止模板中出现 TypeScript 错误,您可以在设置中获取并转换插槽名称。

理想情况下,您可以获得实际类型,而不仅仅是转换为“默认”

<template
  v-for="(slot, index) of slotNames"
  :key="index"
  #[slot]
>
  <slot :name="slot" />
</template>

<script lang="ts" setup>
import { useSlots } from "vue";


const slots = useSlots();

// Assert type here to prevent errors in template
const slotNames = Object.keys(slots) as "default"[];

</script>


1
投票

这里是一个使用 Vuetify Playground 的示例演示 Vue 3 动态槽/模板传递

    <template #[name] v-for="slot, name in $slots">
      <slot :name="name"></slot>
    </template>

enter image description here


0
投票

进一步建立以前的答案:

<template v-for="(_, name) in $slots" #[name]="scope">
  <slot :name v-bind="scope" />
</template>

使用 Vue 3.4 中引入的

v-bind
简写并启用作用域插槽属性

© www.soinside.com 2019 - 2024. All rights reserved.