需求:uniapp使用swiper組件時,內部圖片高度不統(tǒng)一,組件可以根據圖片高度自適應。
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部分
//一開始獲取到圖片數據時,要延時動態(tài)設置一下
// 初始化輪播圖第一屏高度
setTimeout(()=>{
this.setSwiperHeight();
},100)
// 輪播圖切換動態(tài)改變高度
changeSwiper(e) {
this.currentIndex = e.detail.current;
//動態(tài)設置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%;
}
至此,功能完成,特此記錄!