在vue项目中使用swiper实现轮播
1,安装swiper插件——这里我们安装指定版本@3.4.2
npm install swiper@3.4.2 --save
2,安装成功,我们可在项目文件package.json中查看安装版本
3,定义swiper组件页面
(1)在页面引入
<script>
import swiper from "swiper";
</script>
<style scoped>
@import "../../../node_modules/swiper/dist/css/swiper.css";
</style>
(2) template加入结构
<template>
<div class="swiper-container">
<!-- 需要进行轮播的部分 -->
<div class="swiper-wrapper">
<!-- 每个节点 -->
<div class="swiper-slide">
<img src="static/images/banner01.jpg" alt="图片1" />
</div>
<div class="swiper-slide">
<img src="static/images/banner02.jpg" alt="图片2" />
</div>
<div class="swiper-slide">
<img src="static/images/banner03.jpg" alt="图片3" />
</div>
</div>
<!--如果需要使用分页器-->
<div class="swiper-pagination swiper-pagination-white"></div>
<!-- 如果需要使用前进后退按钮 -->
<div class="swiper-button-prev swiper-button-white"></div>
<div class="swiper-button-next swiper-button-white"></div>
</div>
</template>
(3)轮播图运行方法设置
mounted() {
this.initSwiper();
},
methods: {
initSwiper() {
new Swiper(".swiper-container", {
//设置轮播的循环方式
loop: true,
//设置自动播放间隔时间
autoplay: 2000,
// 轮播效果,默认为平滑轮播
effect: "slide",
//分页器
pagination: ".swiper-pagination",
//前进后退按钮
prevButton: ".swiper-button-prev",
nextButton: ".swiper-button-next",
// 用户中断轮播后续播
autoplayDisableOnInteraction: false,
});
},
}
(4)轮播结构样式
//设置轮播图整体宽度/高度
.swiper-container {
width: 100%;
height: 1.8rem;
}
//轮播图左/右按钮盒子
.swiper-button-prev,.swiper-button-next{
height: 0.25rem;
width: 0.25rem;
}
//图片部分样式
.swiper-slide img {
width: 100%;
object-fit: cover;
}