Requirements: The carousel swiper is highly adaptive according to the content image.
However, uni.createSelectorQuery
the height of the picture obtained through uniapp is incorrect. For example, the picture is 100 and the obtained value is 200. It this.$nextTick
cannot be solved. It can be solved, setTimeout
but it is unstable. Sometimes it can be correct in 200ms, sometimes it cannot. If it is set longer, the user experience will not be good. , the picture waiting time is too long
After some research, e.detail.height
the image height can also be obtained in the image loading completion time @load, but the returned image height is still incorrect, which is too confusing, but uni.createSelectorQuery
the method used in load to obtain the image height is correct.
<template>
<swiper class="swiper" @change="viewChange" :autoplay="true" circular :indicator-dots="false" v-if="imgsList.length" :style="[{ height: swiperHeight + 'px' }]">
<swiper-item v-for="item in imgsList" :key="item.id">
<view class="swiper-item uni-bg-red" @click="clickBreak(item)">
<image :src="item.clientFileUrl" mode="widthFix" class="img" @load="loadImg"></image>
</view>
</swiper-item>
</swiper>
</template>
<script>
export default {
name: 'swiperImg',
props: {
imgsList: Array,
},
data() {
return {
swiperHeight: 0,
current: 0,
};
},
methods: {
loadImg() {
this.getCurrentSwiperHeight('.img');
},
// 轮播切换
viewChange(e) {
this.current = e.target.current;
this.getCurrentSwiperHeight('.img');
},
// 动态获取内容高度
getCurrentSwiperHeight(element) {
let query = uni.createSelectorQuery().in(this);
query.selectAll(element).boundingClientRect();
query.exec((res) => {
// 切换到其他页面swiper的change事件仍会触发,这时获取的高度会是0,会导致回到使用swiper组件的页面不显示了
if (this.imgsList.length && res[0][this.current].height) {
this.swiperHeight = res[0][this.current].height;
}
});
},
},
};
</script>
<style lang="scss" scoped>
.swiper {
padding: 0 20rpx;
margin-top: 5px;
margin-bottom: 1px;
border-radius: 4px 4px 4px 4px;
.swiper-item {
width: 100%;
image {
width: 100%;
}
}
}
</style>