vue 父级组件向动态组件传递slot(多层组件传递 slot)

vue 父级组件向动态组件传递slot

需求描述

  • 多层组件 A->B->C
  • B中有动态组件 <component :is="动态组件" />,根据情况在C1 C2 C3(统称为C)中切换
  • A要经由B向C传递slot

错误写法、原因

错误写法:(伪代码)

<!-- 组件A -->
<组件B>
	<template v-slot:buttons> buttons </template>
</组件B>
<!-- 组件B -->
<component :is="component">
	<slot name="buttons"></slot>
</component>
<!-- 组件C -->
<section>
	<header>组件C</header>
	<slot name="buttons"></slot>
</section>

错误原因:A向B传递了 slot:buttons, B也接受了。但是B没有向C传递slot
在这里插入图片描述

正确写法

把组件B改成:

<!-- 组件B -->
<component :is="component">
	<!-- B向C传递slot -->
	<template v-slot:buttons>
		<slot name="buttons"></slot>
	</template>		
</component>

改成不同名字,方便理解

B组件中,从 A拿到的slot给C传递的 slot 的名称是可以不一样的。
下面给他们改成不同名字,这样更容易理解传递的过程:

<!-- 组件A -->
<组件B>
	<template v-slot:slotHello> Hello </template>
</组件B>
<!-- 组件B -->
<component :is="component">
	<template v-slot:slotWorld>
		<span>你好呀</span>
		<slot name="slotHello"></slot>
	</template>		
</component>
<!-- 组件C -->
<section>
	<header>组件C</header>
	<slot name="slotWorld"></slot>
</section>

最终插槽中的内容是:你好呀 Hello


多层组件传递 slot

其实,上面出现的错误写法和动态组件没什么关系,就是多层组件传递slot的问题。

下面的代码演示了多层组件传递slot的多种情形:

<!-- Home.vue -->
<father>
  <template v-slot:fatherSlot1>
    <span> Home传给Father </span>
  </template>
</father>
<!-- Father.vue -->
<section>
  <son>
    <template v-slot:sonSlot1>
      <template v-if="$slots.fatherSlot1">
        <span> 这里是Father,我收到 Home 传来的 fatherSlot1 插槽:</span>
        <slot name="fatherSlot1"></slot>
      </template>
      <span v-else class="blue">这里是Father,我没有收到Home传来的 fatherSlot1 插槽</span>
    </template>
    <template v-slot:sonSlot2>
      <template v-if="$slots.fatherSlot2">
        <span> 这里是Father,我收到 Home 传来的 fatherSlot2 插槽:</span>
        <slot name="fatherSlot2"></slot>
      </template>
      <span v-else>这里是Father,我没有收到Home传来的 fatherSlot2 插槽</span>
    </template>
    <template v-slot:sonSlot3>
      <span>Father 向 Son 传递 sonSlot3 插槽 </span>
    </template>
  </son>
</section>
<!-- Son.vue -->
<section>
  <p>
    sonSlot1:
    <slot name="sonSlot1">sonSlot1 没有接收到 Father 传来的同名插槽</slot>
  </p>
  <p>
    sonSlot2:
    <slot name="sonSlot2">sonSlot2 没有接收到 Father 传来的同名插槽</slot>
  </p>
  <p>
    sonSlot3:
    <slot name="sonSlot3">sonSlot3 没有接收到 Father 传来的同名插槽</slot>
  </p>
  <p>
    sonSlot4:
    <slot name="sonSlot4">sonSlot4 没有接收到 Father 传来的同名插槽</slot>
  </p>
</section>

结果:
在这里插入图片描述

  • 17
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值