uniapp或小程序多级插槽slot会失效

项目场景:

uniapp 中使用 slot 插槽让用户自定义图标,插槽嵌套有三层(多层)会发现插槽失效的行为, 小程序端总是显示默认内容, H5端正常。

<slot name="customIcon">
	<img src="home.png" />  <!-- 默认内容 --->
</slot>

问题描述

举例什么是多级嵌套使用插槽?

例如:有一个Box组件,有两种Box类型:left 和 right,Box组件里面含有图标。多层级情况下,这时候Vue怎么去定义一个自定义图标的插槽 customIcon 呢?

<!-- Box.vue -->
<template>
	<div v-if="type == 'left'">
		<left-box>
			<template v-slot="customLeftIcon">
				<slot name="customIcon"></slot>
			</template>
		</left-box>
	</div>
	<div v-else-if="type == 'right'">...</div>
</template>
<!-- LeftBox.vue -->
<template>
	<div class="leftBox">
		<slot name="customLeftIcon">
			<img src="home.png" />
		</slot>
		<span>i am left box</span>
	</div>
</template>

使用这个Box组件并使用 customIcon 自定义图标用法如下:

<!-- 使用方法 -->
<template>
	<Box type="left">
		<img src="myHome.png" slot="customIcon" />
	</Box>
</template>

以上例子是H5环境的写法,如果没有自定义图标就会使用默认的图标,但是在微信小程序端,这个方式出来的效果就是无论有没有自定义图标都会使用默认的,这符合最终的效果。

坑1

小程序端,我尝试用这样的方法解决问题:手动判断用户有没有使用自定义插槽 $slots[‘customIcon’], 只有自定义了才会在子组件设置插槽。这里我不会再写使用方法,主要写实现:

<!-- Box.vue -->
<template>
	<div v-if="type == 'left'">
		<left-box>
			<template v-slot="customLeftIcon" v-if="$slots['customIcon']">
				<slot name="customIcon"></slot>
			</template>
		</left-box>
	</div>
	<div v-else-if="type == 'right'">...</div>
</template>

LeftBox.vue 与原来一致,最终效果不达标

坑2

搜了很多资料,说是 v-if 判断只能放置在里面,我把它改成这样:

<!-- Box.vue -->
<template>
	<div v-if="type == 'left'">
		<left-box>
			<template v-slot="customLeftIcon">
				<slot name="customIcon" v-if="$slots['customIcon']"></slot>
			</template>
		</left-box>
	</div>
	<div v-else-if="type == 'right'">...</div>
</template>

还是不行!


原因分析:

这个原因我不知道,也不想知道,更加不愿意知道,奇奇怪怪的问题,只能归结为小程序插槽的坑。

解决方案:

有效的解决办法:

父组件Box传一个 isCustomIcon 进去:

<!-- Box.vue -->
<template>
	<div v-if="type == 'left'">
		<left-box :isCustomIcon="!!$slots['customIcon']">
			<template v-slot="customLeftIcon">
				<slot name="customIcon"></slot>
			</template>
		</left-box>
	</div>
	<div v-else-if="type == 'right'">...</div>
</template>
<!-- LeftBox.vue -->
<template>
	<div class="leftBox">
		<!-- 父组件传来的 isCustomIcon -->
		<template v-if="isCustomIcon">
			<slot name="customLeftIcon" />
		</template>
		<img v-else src="home.png" />
		<span>i am left box</span>
	</div>
</template>

这样就没有问题了!

猜你喜欢

转载自blog.csdn.net/qq_44622894/article/details/125931309