Vue3+swiper5 异步请求数据后轮播图出现无分页器小圆点和无法滑动的问题,如果有默认图片则从最后一张切换到第一张时会展示默认图片

一、场景描述

异步请求获取到11张图片,页面播图无分页器小圆点和无法正常滑动。
在这里插入图片描述

//package.json:
"devDependencies": {
    "@vue/cli-plugin-babel": "^4.5.13",
    "@vue/cli-plugin-router": "^4.5.13",
    "@vue/cli-plugin-vuex": "^4.5.13",
    "@vue/cli-service": "^4.5.13",
    "@vue/compiler-sfc": "^3.2.6",
    "less": "^3.13.1",
    "less-loader": "^5.0.0",
    "swiper": "^5.3.6",
    "vue-awesome-swiper": "^4.1.1"
  }

二、出现异常问题时的代码

<template>
  <div class="swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="(item, index) in imgs" :key="index">
        <img :src="item.pic" />
      </div>
    </div>
    <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>
  </div>
</template>

<script>
import "swiper/css/swiper.css";
import Swiper from "swiper";
import axios from "axios";

export default {
  name: "swiperCom",
  data() {
    return {
      imgs: [],
    };
  },
  methods: {
    carouselScroll() {
      var mySwiper = new Swiper(".swiper-container", {
        loop: true, // 循环模式选项

        // 如果需要分页器
        pagination: {
          el: ".swiper-pagination",
          clickable: true,
        },
      });
    },
  },
  async mounted() {
    this.carouselScroll();
    let result = await axios.get("http://localhost:3000/banner?type=1");
    this.imgs = result.data.banners;
    //在异步请求成功后重新初始化轮播图,但不起效果
     this.$nextTick(() => {
      mySwiper.init();
    });
  },
};
</script>


<style lang="less">
.swiper-container {
  width: 7.1rem;
  height: 2.6rem;
  border-radius: 0.1rem;
  .swiper-slide {
    img {
      width: 100%;
    }
  }
}
.swiper-pagination-bullet-active {
  background-color: orangered;
}
</style>

三、更正后的代码

//
 methods: {
    carouselScroll() {
      var mySwiper = new Swiper(".swiper-container", {
        loop: true, // 循环模式选项

        // 如果需要分页器
        pagination: {
          el: ".swiper-pagination",
          clickable: true,
        },
      });
    },
  },
  async mounted() {
    let result = await axios.get("http://localhost:3000/banner?type=1");
    this.imgs = result.data.banners;
    //在异步请求成功后再定义轮播图即可
     this.$nextTick(() => {
      this.carouselScroll();
    });
  },
/*
方法2:使用updated钩子函数,意思跟$nextTick一样,在DOM更新完成后再重新渲染
updated(){
	this.carouselScroll();
}
*/

四、错误代码在有默认图片时,异步请求后会出现分页器小圆点,但是最后一张切换到第一张时会展示默认图片。代码更改后则不再出现了

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值