uni-app swiper子组件判断有问题

uni-app swiper子组件判断有问题

开发环境 版本号 项目创建方式
Windows 10 HBuilderX

示例代码:

父组件:

<template>  
    <swiper><sub> <!-- 引入子组件 --></sub></swiper>  
</template>

子组件

<template>  
    <swiper-item><text>123</text></swiper-item>  
</template>

更多关于uni-app swiper子组件判断有问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app swiper子组件判断有问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在 uni-app 中,swiper 组件直接嵌套自定义子组件时,确实容易出现渲染问题。这是因为 swiper 的机制要求其直接子节点必须是 swiper-item,而自定义组件在编译后可能被包裹一层容器,导致 swiper 无法正确识别子组件结构。

解决方案:

  1. 直接使用 swiper-item
    在父组件中直接使用 swiper-item,避免通过子组件封装:

    <template>
      <swiper>
        <swiper-item><text>123</text></swiper-item>
        <swiper-item><text>456</text></swiper-item>
      </swiper>
    </template>
    
  2. 使用 slot 传递内容
    如果子组件逻辑复杂,可将 swiper-item 放在父组件,内容通过 slot 传递给子组件:

    <!-- 父组件 -->
    <template>
      <swiper>
        <swiper-item v-for="item in list">
          <sub-component :content="item.content" />
        </swiper-item>
      </swiper>
    </template>
    
  3. 动态渲染子组件
    通过 v-for 动态生成 swiper-item,将数据传递给子组件:

    <template>
      <swiper>
        <swiper-item v-for="(item, index) in dataList" :key="index">
          <custom-component :data="item" />
        </swiper-item>
      </swiper>
    </template>
回到顶部