我无法循环遍历 Vue 3 中的 $slots 对象以将所有插槽从父组件传递到子组件,$slots 对象在子组件中似乎为空。
如何循环遍历 $slots 对象以将所有父插槽传递给子组件?
运行代码时出现此错误: 类型错误:无法读取 null 的属性(读取“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>
您必须使用 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>
为了防止模板中出现 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>
这里是一个使用 Vuetify Playground 的示例演示 Vue 3 动态槽/模板传递:
<template #[name] v-for="slot, name in $slots">
<slot :name="name"></slot>
</template>