微信小程序插槽透传在uni-app中会导致子节点无法渲染插槽的默认值

微信小程序插槽透传在uni-app中会导致子节点无法渲染插槽的默认值

开发环境 版本号 项目创建方式
Windows 11 24H2 HBuilderX

产品分类:uniapp/小程序/微信

示例代码:

A文件

<script setup>  
  import Parent from './Parent.vue'  
</script>  

<template>  
  <view class="box">  
    <view>使用插槽默认值</view>  
    <Parent />  
  </view>  
  <view class="box">  
    <view>使用插槽</view>  
    <Parent>  
      <template #child>  
        <view>我是外部插槽</view>  
      </template>  
    </Parent>  
  </view>  
</template>  

<style>  
  .box{  
    margin: 20px 10px;  
  }  
</style>

b文件

<template>  
  <view class="">  
    <view>这是Parent组件</view>  
    <Child>  
      <template v-if="hasSlot" #child>  
        <slot name="child"></slot>  
      </template>  
    </Child>  
  </view>  
</template>  

<script setup>  
  import {  
    computed,  
    useSlots  
  } from 'vue';  
  import Child from './Child.vue'  
  const slotMap = useSlots()  
  console.log('parent slotMap ->', slotMap)  

  const hasSlot = computed(() => !!slotMap.child)  
</script>  

<style>  
</style>

c文件

<template>  
  <view>  
    <view class="">  
      这是Child组件  
    </view>  
    <slot v-if="hasSlot" name="child" />  
    <view v-else>我是插槽默认值</view>  
  </view>  
</template>  

<script setup>  
  import {  
    computed,  
    useSlots  
  } from 'vue';  
  import Child from './Child.vue'  
  const slotMap = useSlots()  
  console.log('slotMap ->', slotMap)  
  const hasSlot = computed(() => !!slotMap.child)  
</script>  

<style>  
</style>

更多关于微信小程序插槽透传在uni-app中会导致子节点无法渲染插槽的默认值的实战教程也可以访问 https://www.itying.com/category-93-b0.html

8 回复

vue版本是多少?其他小程序有没有这问题?

更多关于微信小程序插槽透传在uni-app中会导致子节点无法渲染插槽的默认值的实战教程也可以访问 https://www.itying.com/category-93-b0.html


vue版本3.4.21,暂时没有兼容其他小程序的需求,其他小程序我没有测试。

确实,我是想在组件中获取设置的 slot 内容,小程序端查找的数据是个 boolean 类型,实际应该是个对象,在 h5 环境下是正常的。
const slots = useSlots()
console.log(slots) 通过 slots.default() 获取 slot 内容
h5 打印出来的 slots {
default(), // 这是个方法,
} 小程序打印出来的 slots {
default: true, // 这是个 boolean 值
} 如下图(微信小程序):

小程序端有限制

回复 DCloud_UNI_JBB: 那需要怎么解决这样的问题,有替代方案吗

回复 Dodu: 没有

这是一个典型的插槽透传场景中的条件渲染问题。在uni-app的微信小程序环境中,插槽透传时子组件无法正确检测到插槽内容的存在。

问题分析:

  1. 插槽检测机制:在Parent组件中,useSlots().child检测到有插槽内容,所以hasSlot为true,Child组件被传入#child插槽
  2. 透传失效:当Parent组件将插槽透传给Child组件时,Child组件中的useSlots().child无法检测到这个透传的插槽内容
  3. 条件渲染冲突:Parent组件认为有插槽内容,但Child组件认为没有,导致v-else分支执行,显示默认值

解决方案:

修改Parent组件,移除条件判断,直接透传插槽:

<template>  
  <view class="">  
    <view>这是Parent组件</view>  
    <Child>  
      <slot name="child"></slot>  
    </Child>  
  </view>  
</template>  

<script setup>  
  import Child from './Child.vue'  
</script>
回到顶部