美文网首页
uniapp低效率但很有效的解决swiper高度自适应问题

uniapp低效率但很有效的解决swiper高度自适应问题

作者: 锋叔 | 来源:发表于2021-06-30 19:34 被阅读0次

uniapp新手使用到这个插件时基本上难以避免的坑,网上解决方法不少,我目前找了一个感觉性能上可能不太好的,但起码简单有效。

上代码

<template>
  <view>
    <swiper
      :autoplay="false"
      @change="changeSwiper"
      :current="currentIndex"
      :style="{ height: swiperHeight + 'px' }"
    >
      <swiper-item v-for="(item, index) in dataList" :key="item.id">
        <view :id="'content-wrap' + index">
            每一个swiper-item的内容区域
            ....
        </view>
      </swiper-item>
    </swiper>   
  </view>
</template>

<script>
export default {
  data() {
    return {
      //滑块的高度(单位px)
      swiperHeight: 0,
      //当前索引
      currentIndex: 0,
      //列表数据
      dataList: [],
    };
  },
  created() {
    //动态设置swiper的高度
    this.$nextTick(() => {
      this.setSwiperHeight();
    });
  },
  methods: {
    //手动切换题目
    changeSwiper(e) {
      this.currentIndex = e.detail.current;
      //动态设置swiper的高度,使用nextTick延时设置
      this.$nextTick(() => {
        this.setSwiperHeight();
      });
    },
    //动态设置swiper的高度
    setSwiperHeight() {
      let element = "#content-wrap" + this.currentIndex;
      let query = uni.createSelectorQuery().in(this);
      query.select(element).boundingClientRect();
      query.exec((res) => {
        if (res && res[0]) {
          this.swiperHeight = res[0].height;
        }
      });
    },
  },
};
</script>

<style lang="scss">

</style>
  • 思路就是给每个swiper-item下面的内容加一个id,根据元素id获取高度,然后用nextTick把这个的高度赋值给swiper组件。这个性能肯定是不好的,因为使用了nextTick和获取元素的高度,这都是会造成js性能问题。哎,但是有什么办法呢!!先解决问题再说把,如果哪位大佬有更好的方法,欢迎指教。

相关文章

网友评论

      本文标题:uniapp低效率但很有效的解决swiper高度自适应问题

      本文链接:https://www.haomeiwen.com/subject/drzrultx.html