【uniapp】swiper组件高度自适应问题

场景

使用uniapp中的swiper组件进行轮播,swiper组件高度是在外层有个默认高度,并没有去适配里面的内容高度。

解决

计算出内容高度height,然后使用动态绑定style的方式将内容高度重新复制给swiper组件。(由于我的swiper内容区包含图片资源,图片资源没有加载完导致内容区高度计算出错,所以我将高度计算放在图片资源加载完成后)

      <swiper class="swiper" :indicator-dots="indicatorDots" :circular="circular" indicator-active-color="#feba50" :style="{height: listHeight}">
            <swiper-item v-for="(item, index) in prizeList" :key="index">
                <view class="swiper-item">
                    <img class="ui" :src="item.iu" alt=""  @load="fixSwiperHeight('.swiper-item')"></img>
                    <view style="font-size:18px;font-weight:700;">{{item.l}}等奖:{{item.n}}</view>
                    <view style="font-size:16px;">{{item.desc}}<span style="font-size:20px;color:red;">{{item.p}}</span></view>
                    <view class="left-tag">
                        <view class="grade">{{item.l}}</view>
                        <view class="desc">等奖</view>
                    </view>
                </view>
            </swiper-item>
      </swiper>


    fixSwiperHeight(className: string){
		let _this = this
		let info = uni.createSelectorQuery().select(className);
		info.boundingClientRect((data: any) => {
            _this.listHeight = data.height + 30 + 'px'; 
		}).exec();
	}

经测试第一种方法在图片资源过大的情况下会获取不到高度,所以更换图片高度获取方式

        <swiper :circular="circular" :indicator-dots="indicatorDots" :style="{height: listHeight}" class="swiper"
                indicator-active-color="#feba50">
            <swiper-item :key="index" v-for="(item, index) in proImgList">
                <view class="swiper-item">
                    <img :src="item" @load="fixSwiperHeight" alt="" class="ui" ref="proImg"></img>
                </view>
            </swiper-item>
        </swiper>

        fixSwiperHeight() {
            let _this = this
            let proImg: any = this.$refs.proImg;
            this.listHeight = proImg[0].height + 30 + 'px';
        }

版权声明:本文为qq_41595903原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。