Vue通过动态组件向孙组件传递slot 自定义内容不生效如何解决
问题原因
核心问题有两个:
- 插槽名称不匹配:Wrapper 组件循环渲染时定义的插槽名称为
Child1、Child2,但 App.vue 中传入的插槽名称为slot1、slot2,导致 Wrapper 根本无法接收到传入的自定义内容。 - 插槽未透传:Vue 的插槽作用域是独立的,你在 App.vue 中声明的
slot="top"是属于 Wrapper 组件的插槽,不会自动传递给 Wrapper 内部渲染的 Child1/Child2 组件,所以子组件拿不到对应内容。
修复方案
这里提供最简洁的实现方案,不需要大幅调整原有逻辑:
步骤1:修改 Wrapper.vue,添加插槽透传逻辑
将动态组件部分的代码修改为如下,实现插槽自动匹配透传:
<template> <component v-for="c of comps" :key="c.componentName" :is="c.componentName" > <!-- 匹配格式为「子组件名:插槽名」的插槽,透传给对应子组件的对应插槽 --> <template v-for="(slotContent, fullSlotName) in $scopedSlots" v-slot:[slotName]="slotProps" :key="fullSlotName" v-if="fullSlotName.startsWith(`${c.componentName}:`)" > <slot :name="fullSlotName" v-bind="slotProps" /> </template> </component> </template> <script> export default { data() { return { comps: [ { componentName: "Child1" }, { componentName: "Child2" } ] } } } </script>
如果是 Vue3 环境,将代码中的
$scopedSlots替换为$slots即可。
步骤2:修改 App.vue 的插槽使用方式
按照「子组件名:插槽名」的命名约定传入内容即可:
<Wrapper> <template v-slot:Child1:top>Inner Content1</template> <template v-slot:Child2:top>Inner Content2</template> </Wrapper>
修改后即可正常展示你传入的自定义内容,子组件的默认插槽内容会被覆盖。
内容的提问来源于stack exchange,提问作者Ayush Kumar
相关产品推荐
相关产品推荐

