基础入门:父组件调用子组件插槽传递方案

  1. 在子组件child.vue定义了名为solt1的命名插槽
<template>
   这是子组件
	<slot name="slot1"></slot1>
</template>
  1. 在父组件引用child.vue组件,并向插槽中传递自定义模版代码进行渲染
<template>
	这是父组件
	<child>
			<template #slot1>
         <a-input>
			</template>
	</child>
</template>

3.这样在组件运行时,就能将input 渲染到合适的位置上去。

插槽进阶:

如果子组件内调用了另一个子组件2,在子组件2中如何需要插槽渲染,父组件如何将插槽传递给子组件2中呢?

  1. 在子组件child2.vue定义了名为solt2的命名插槽
<template>
   这是子组件
	<slot name="slot2"></slot1>
</template>
  1. 在子组件child1.vue中调用了子组件child2.vue; 子组件1只是一个桥梁,
<template>
	 <slot name="slot2"></slot1> <!--此处正常渲染input-->
   这是子组件
   <child2>
			<slot name="slot2"></slot1> <!--此处无法渲染input-->
	</child2>
	
</template>
  1. 在父组件引用child2.vue组件,并向插槽中传递自定义模版代码希望渲染到child2组件内使用
<template>
	这是父组件
	<child1>
			<template #slot1>
         <a-input>
			</template>
	</child1>
</template>
  1. 运行之后,发现inpit在child1中得到了渲染,但是没有传递到child2中,应该是在child1中被阻断了

解决插槽的深度传递

child1进行改造; 这样任何插槽都能传递到child2组件中。如果有更深层,则每一层都要加上这个代码;此处是vue2语法,vue3语法不一样,解决方案就是这样。

<template>
	 <slot name="slot2"></slot1> <!--此处正常渲染input-->
   这是子组件
   <child2>
			<template v-for="name in Object.keys($scopedSlots)" #[name]="scope">
				<slot :name="name" v-bind="scope"/>
			</template>
	</child2>
	
</template>
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐