uni-app 关于组件插槽内容不显示的问题
uni-app 关于组件插槽内容不显示的问题
信息类别 | 详情 |
---|---|
产品分类 | uniapp/小程序/微信 |
PC开发环境 | Windows |
操作系统版本 | 10 |
第三方工具 | 1.06.2404301 win32-x64 |
基础库版本 | 3.43 |
项目创建方式 | CLI |
CLI版本 | 3.0.0-4010420240430001 |
示例代码:
子组件代码
<template>
<view class="base-page">
<slot :user="{ id: 1, name: '张三' }"></slot>
</view>
</template>
父组件(页面)代码中的插槽内容不显示
<template>
<base-page>这里是插槽内容</base-page>
</template>
父组件(页面)代码中的插槽内容不显示
<template>
<base-page>
<template #default>这里是插槽内容</template>
</base-page>
</template>
父组件(页面)代码中的插槽内容这样写才显示
<template>
<base-page>
<template #default="{}">这里是插槽内容</template>
</base-page>
</template>
操作步骤:
请查看上面的代码示例
预期结果:
希望下面两种方式的写法也显示,H5上是没问题的
父组件(页面)代码中的插槽内容不显示
<template>
<base-page>这里是插槽内容</base-page>
</template>
父组件(页面)代码中的插槽内容不显示
<template>
<base-page>
<template #default>这里是插槽内容</template>
</base-page>
</template>
实际结果:
请查看上面的代码示例
bug描述:
在微信小程序环境中,如果组件内的 slot
上有插槽 prop,父组件在使用该组件时(但是不使用提供的插槽数据),这时父组件中传入的插槽内容就不会显示
更多关于uni-app 关于组件插槽内容不显示的问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html
1 回复
更多关于uni-app 关于组件插槽内容不显示的问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在 uni-app
中,使用组件插槽时,如果插槽内容不显示,可能是由于以下几个原因导致的。以下是一些常见的排查和解决方法:
1. 插槽未正确传递
确保父组件中正确传递了插槽内容。
<!-- 父组件 -->
<MyComponent>
<template v-slot:default> 默认插槽内容 </template>
<template v-slot:header> 头部插槽内容 </template>
</MyComponent>
在子组件中,确保正确使用了 <slot>
标签:
<!-- 子组件 MyComponent.vue -->
<template>
<div>
<slot name="header"></slot>
<slot></slot> <!-- 默认插槽 -->
</div>
</template>
2. 插槽作用域问题
如果使用作用域插槽,确保正确传递了插槽作用域数据。
<!-- 父组件 -->
<MyComponent>
<template v-slot:default="slotProps">
{{ slotProps.data }}
</template>
</MyComponent>
子组件中需要绑定数据:
<!-- 子组件 MyComponent.vue -->
<template>
<div>
<slot :data="someData"></slot>
</div>
</template>
3. 样式或布局问题
检查是否有样式或布局导致插槽内容被隐藏。例如:
display: none
或visibility: hidden
。- 父容器高度为
0
或overflow: hidden
。 z-index
层级问题。
可以通过开发者工具检查插槽内容的 DOM 是否存在,以及其样式是否符合预期。
4. 条件渲染问题
如果插槽内容使用了 v-if
或 v-show
,确保条件判断正确。
<MyComponent>
<template v-slot:default v-if="shouldShow">
默认插槽内容
</template>
</MyComponent>
5. 插槽名错误
确保插槽名匹配。默认插槽不需要命名,但具名插槽需要确保名称一致。
<!-- 父组件 -->
<MyComponent>
<template v-slot:customSlot> 内容 </template>
</MyComponent>
<!-- 子组件 -->
<template>
<div>
<slot name="customSlot"></slot>
</div>
</template>