需求:轮播图swiper根据内容图片高度自适应

但是通过uniapp uni.createSelectorQuery的方法获取图片高度不正确,比如图片是100,获取是200,this.$nextTick也不能解决,setTimeout到是能解决,但是不稳定,有时200ms能正确,有时不能,再设置久一点,用户体验不好,图片等待时间太久了

研究了一下,图片加载完成时间@load里,也能e.detail.height获取图片高度,但返回的图片高度还是不正确,太坑了,但load里再使用uni.createSelectorQuery的方法获取图片高度则正确了

<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>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐