uniapp使用swiper动态获取高度为null、切换时不能动态获取高度问题的解决

遇到的问题

  • 问题:
    uni-app开发小程序,使用swiper组件时内容高度不固定,需要动态获取高度;

    使用uni.createSelectorQuery()方法获取一直为null,且切换swiper时不能动态切换高度;

    这里swiper的数据是动态渲染的(静态数据时不存在这个问题)

  • 原因:

    • 1.uni.createSelectorQuery()获取一直为null
      • 检查是否使用$nextTick包裹
      • 如包裹后仍获取不到可再尝试增加延时器setTimeout
    • 2.切换swiper时不能动态切换高度
      • 可将swiper-item中的内容使用scroll-view包裹

解决

  • 实现代码

    <!-- .vue页面文件 -->
    <template>
    	...
    	<!-- swiper组件,只展示了核心代码配置 -->
    	<swiper :style="'height:'+ plateHeight +'px;'" :current="hotPlateActive" @change="plateSwiperChange">
    		<swiper-item v-for="(p,pindex) in hotPlateData" :key="pindex">
    			<scroll-view v-if="pindex === hotPlateActive">
    				<view class="new" id="plateHeight">......</view>
    			</scroll-view>
    		</swiper-item>
    	</swiper>
    	...
    </template>
    
    <script>
      export default {
      	data(){
            hotPlateData: [...], // swiper数据
            hotPlateActive: 0, // 选中的项
            plateHeight: null, // swiper的高度
      	},
      	...
      	onLoad() {
            this.getData()
      	},
      	methods: {
      		getData() {
      			// 获取swiper数据
                ...... 
              	// 动态获取高度  
                self.$nextTick(() => {
                    setTimeout(function() {
                        // 获取模块的高度
                        let query1 = uni.createSelectorQuery()
                        query1.select("#plateHeight").boundingClientRect()
                        query1.exec(res => {
                            if (self.utils.IsExis(res[0])) {
                          	  self.plateHeight = res[0].height
                            }
                        })
                    }, 10);
                })
      		},
      		// 切换swiper
            plateSwiperChange(e) {
                var self = this
                self.hotPlateActive = e.detail.current
                self.$nextTick(() => {
                    setTimeout(function() {
                    // 获取板块天梯模块的高度
                    let query1 = uni.createSelectorQuery()
                    query1.select("#plateHeight").boundingClientRect()
                    query1.exec(res => {
                        if (self.utils.IsExis(res[0])) {
                       	 self.plateHeight = res[0].height
                        }
                        })
                    }, 10);
                })
            },
        }
      }
    

  • 29
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值