vue & swiper——关于与后端交互的几个建议

关于与后端交互的几个建议

建议一

请求数据后再初始化swiper实例

理由

一开始我是按照GitHub上的文档配置swiper的:

<template>
  <swiper :options="swiperOption">
    <swiper-slide v-for="slide in swiperSlides">I'm Slide {{ slide }}</swiper-slide>
    <div class="swiper-pagination" slot="pagination"></div>
  </swiper>
</template>

<script>
  export default {
    name: 'carrousel',
    data() {
      return {
        swiperOption: {
          pagination: {
            el: '.swiper-pagination'
          }
        },
        swiperSlides: [1, 2, 3, 4, 5]
      }
    },
    mounted() {
      setInterval(() => {
        console.log('simulate async data')
        if (this.swiperSlides.length < 10) {
          this.swiperSlides.push(this.swiperSlides.length + 1)
        }
      }, 3000)
    }
  }
</script>

然后在mounted中请求自己的数据,把请求到的数据放到swiperSlides中,结果发现轮播的时候出现错误,轮播到最后一个时再往后轮播就会回到第二个,不会回到第一个。

这个时候就比较头疼了,找了很久都找不到原因,最后想到一个方法就是先请求到数据再初始化swiper这个实例,最后就可以了。

附上代码:

method: {
	async getList() {
      const _self = this;
      try {
        const res = await getList();
        const { list } = res.data.page;
        this.carouselList = list;

        this.$nextTick(() => {
          this.swiper = new Swiper('.swiper-container', {
            pagination: '.swiper-pagination',
            autoplay: 5000,
            autoplayDisableOnInteraction: false,
            onlyExternal: false,
            initialSlide: 0,
            loop: true,
            onSlideChangeStart(swiper) {
              console.log(swiper.realIndex);
              _self.currentIndex = swiper.realIndex;
            }
          });
          
          if (this.isAutoChange) {
            this.swiper.startAutoplay();
          } else {
            this.swiper.stopAutoplay();
          }
        });
      } catch (err) {
        console.log(err);
      }
    },
}

大功告成!

建议二

再次请求数据前最好先停止自动轮播

理由

如果需要一段时间更新轮播数据,则最好是先停止当前轮播再发送请求

附上代码:

 mounted() {
   this.getList();
   this.dataTimer = setInterval(() => {
     this.swiper.stopAutoplay();
     this.getList();
   }, 60000);
 },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端技术迷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值