uni-app vue3 组件透传插槽在微信小程序上会导致插槽默认内容无法显示
uni-app vue3 组件透传插槽在微信小程序上会导致插槽默认内容无法显示
操作步骤:
- 下载附件项目 test1.zip
- 运行至浏览器
- 运行至微信小程序
预期结果:
小程序应该与H5一致,第一个组件调用应该正常显示插槽默认内容。
实际结果:
第一个组件调用在小程序未正常显示插槽默认内容。
bug描述:
有两个组件 compnent1、compnent2,compnent2 继承 compnent1,compnent1 有一个具名插槽 title,
<slot name="title">
<text style="color: red;">title插槽默认内容</text>
</slot>
在最外层调用 compnent2 时需要可以传入自定义 title 插槽内容,因此将 title 插槽透传至 compnent2:
<component1>
<template v-if="$slots.title" #title>
<slot name="title" />
</template>
</component1>
最外层调用:
<component2 />
或者:
<component2>
<template #title>
<text style="color: blue;">顶层传入插槽内容</text>
</template>
</component2>
目前在H5中运行正常,但在小程序中即使最外层未传入插槽内容,component1 的默认内容也无法显示,如图:
H5中运行正常:

小程序中未显示插槽默认内容:

更多关于uni-app vue3 组件透传插槽在微信小程序上会导致插槽默认内容无法显示的实战教程也可以访问 https://www.itying.com/category-93-b0.html
v-if + v-slot 组合起来行为异常是已知问题,会尽快修复
更多关于uni-app vue3 组件透传插槽在微信小程序上会导致插槽默认内容无法显示的实战教程也可以访问 https://www.itying.com/category-93-b0.html
这是一个已知的uni-app在微信小程序平台上的插槽透传问题。在小程序环境中,$slots的检测机制与H5存在差异。
问题核心在于:在微信小程序中,即使未传入插槽内容,$slots.title也可能不为空,导致条件渲染始终进入v-if分支,从而无法显示默认内容。
解决方案:
使用useSlots()组合式API替代$slots:
<component1>
<template v-if="hasTitleSlot" #title>
<slot name="title" />
</template>
</component1>
import { useSlots } from 'vue'
const slots = useSlots()
const hasTitleSlot = computed(() => {
return !!slots.title
})
替代方案:
如果上述方法仍有问题,可以采用更稳定的方式:
<component1>
<template #title>
<slot name="title">
<text style="color: red;">title插槽默认内容</text>
</slot>
</template>
</component1>

