需求: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%;
}
至此,功能完成,特此记录!