一、场景描述
异步请求获取到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();
}
*/
四、错误代码在有默认图片时,异步请求后会出现分页器小圆点,但是最后一张切换到第一张时会展示默认图片。代码更改后则不再出现了