Vue项目中添加轮播效果,使用swiper后,分页器无法正常显示,但轮播效果和前进后退箭头以及滚动栏都是正常显示的,为了解决这一问题,经过研究以及查阅资料得出解决方案,在此整理一下
<template>
<div class="slider">
<div class="swiper-container" v-if="banners.length">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(img, index) in banners" :key="index">
<img :src="img" alt />
</div>
</div>
<div class="swiper-button-next"></div>
<div class="swiper-pagination"></div>
<div class="swiper-button-prev"></div>
</div>
</div>
</template>
<script>
// 引入swiper 6+
import Swiper from "swiper";
import "swiper/swiper.min.css";
import img1 from "@/assets/images/img_1.jpg";
import img2 from "@/assets/images/img_2.jpg";
import img3 from "@/assets/images/img_3.jpg";
export default {
name: "slider",
data() {
return {
banners: []
};
},
mounted() {
this.banners = [img1, img2, img3]
this.$nextTick(() => {
new Swiper(".swiper-container", {
loop: true,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev"
},
pagination: {
el: ".swiper-pagination",
clickable: true
}
});
});
}
};
</script>
<style scoped>
.swiper-wrapper img {
width: 100%;
}
/* 设置前进后退 */
.swiper-container {
--swiper-theme-color: #fff; /* 设置Swiper风格 */
--swiper-navigation-color: #fff; /* 单独设置按钮颜色 */
--swiper-navigation-size: 20px; /* 设置按钮大小 */
}
/* 设置分页 */
.swiper-container {
--swiper-theme-color: #ff6600;
--swiper-pagination-color: #fff; /* 两种都可以 */
}
</style>
不显示的原因是:
是因为生成swiper时机太早,发生在数据更新之前
解决方案
使用watch+$nextTick( () =>{界面更新之后立即执行生成swiper实例})
网友评论