前言
项目中使用的vue,刚好有需求要实现轮播图,突出显示当前图片,两边展示其他图片;通过查各种资料,实现了,故在此记录下来
下面我们来看下实现步骤:
实现效果如下:
第一步:首先在项目index.html中引入swiper的css文件-swiper.min.css
第二部:写入dom结构
v-for="(item, i) in pictures"
:key="i"
class="swiper-slide"
>
:src="item.advertiseImages"
alt="商品图片"
>
复制代码第三步:在项目中使用npm安装swiper模块
npm install swiper --save-dev
复制代码JS中文网 - 前端进阶资源教程 www.javascriptC.com
一个致力于帮助开发者用代码改变世界为使命的平台,每天都可以在这里找到技术世界的头条内容
第四步:在vue文件中引入,并初始化swiper;
先引入swiper
import Swiper from "swiper";
复制代码
注意初始化需要放入mounted钩子中哦
import Swiper from "swiper";
export default {
data() {
return {
}
},
mounted() {
var mySwiper = new Swiper(".swiper-container", {
direction: "horizontal",
loop: false,
slidesPerView: "auto",
centeredSlides: true,
spaceBetween: 20,
observer: true,
observeParents: true
});
}
}
复制代码
如果你的项目中,图片是从后台接口获取,那么上面的初始化可能会出问题,这个时候我们采取另外的方式初始化swiper
import Swiper from "swiper";
export default {
data() {
return {
mySwiper: null
}
},
methods: {
getdata() {
promise.then(res => {
this.pictures = res.images || [];
this.$nextTick(() => {
this.initSwiper();
});
});
},
initSwiper() {
this.mySwiper = new Swiper(".swiper-container", {
direction: "horizontal",
loop: false,
slidesPerView: "auto",
centeredSlides: true,
spaceBetween: 20,
observer: true,
observeParents: true
});
}
}
}
复制代码
把swiper的初始化放入vue的nextTick中执行,就解决掉问题啦
第五步: 写好swiper样式(这里使用的stylus)
.swiper-container
margin-top crem(40)
width crem(750)
height crem(850)
margin-bottom crem(53)
overflow visible!important
.swiper-container .swiper-wrapper .swiper-slide
width crem(620)
border-radius crem(20)
.swiper-container .swiper-wrapper .swiper-slide img
width 100%
height 100%
border-radius crem(20)
.swiper-container .swiper-wrapper .swiper-slide-prev
margin-top crem(18)
height crem(810)!important
.swiper-container .swiper-wrapper .swiper-slide-prev img
height crem(810)!important
.swiper-container .swiper-wrapper .swiper-slide-next
margin-top crem(18)
height crem(810)!important
.swiper-container .swiper-wrapper .swiper-slide-next img
height: crem(810)!important
.swiper-container .swiper-wrapper .swiper-slide-active
width: crem(620)
.swiper-pagination
bottom: crem(-30)!important
// crem 为项目配置rem的全局计算方法
复制代码第六步:如果想获取当前滚动到哪一张图片怎么办呢
this.mySwiper.activeIndex;
复制代码
使用activeIndex属性就可以获取到当前图片的索引啦。
那么我们这个功能就完成啦
❤️ 看完两件事
如果你觉得这篇内容对你挺有启发,我想邀请你帮我两个小忙:
点个「赞」,把这篇内容分享到你的QQ/微信群,让更多的人也能看到 -_-,
关注公众号「IT平头哥联盟」,一起进步,一起成长!
更多文章
JS中文网 - 前端进阶资源教程 www.javascriptC.com
一个致力于帮助开发者用代码改变世界为使命的平台,每天都可以在这里找到技术世界的头条内容