uniapp动态设置swiper图片高度(亲测有效)

需求:uniapp使用swiper组件时,内部图片高度不统一,组件可以根据图片高度自适应。

html部分

<swiper class="swiper" @change="changeSwiper" :current="currentIndex" circular autoplay :style="{ height: swiperHeight + 'px' }">
    <swiper-item v-for="(item,index) in 你的图片数组" :key="index">
        <image :id="'bg'+index" class="bg" :src="图片地址" mode="aspectFill"></image>
    </swiper-item>
</swiper>

data部分

currentIndex: 0,  //当前索引
swiperHeight: 0,  //滑块的高度(单位px)

js部分

//一开始获取到图片数据时,要延时动态设置一下
// 初始化轮播图第一屏高度
setTimeout(()=>{
    this.setSwiperHeight();
 },100)
// 轮播图切换动态改变高度
changeSwiper(e) {
  this.currentIndex = e.detail.current;
  //动态设置swiper的高度,使用nextTick延时设置
  this.$nextTick(() => {
    this.setSwiperHeight();
  });
},
// 设置轮播图高度
setSwiperHeight() {
    let element = "#bg" + this.currentIndex;
    let query = uni.createSelectorQuery().in(this);
    query.select(element).boundingClientRect();
    query.exec((res) => {
        if (res && res[0]) {
            this.swiperHeight = res[0].height;
        }
    })
},
            

css部分

.bg{
  width: 100%;
}

至此,功能完成,特此记录!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容