vue-awesome-swiper的使用
这是swiper专门为了vue开发出的插件,参数基本一样
vue中使用
npm install vue-awesome-swiper
组件中引入
import { Swiper, SwiperSlide } from 'vue-awesome-swiper' import 'swiper/css/swiper.css'
<swiper ref="carouselSwiper" :options="carouselSwiperOptions" v-if="carouselList.length" > <swiper-slide v-for="(item, index) in carouselList" :key="index" > <img class="carouselImg" :src="item.picPath" alt="carousel图片"> <div class="swiper-slide-title">{{item.title}}</div> <div class="swiper-title-bgc"></div> </swiper-slide> <div class="swiper-pagination" slot="pagination"></div> <div class="swiper-button-prev" slot="button-prev"></div> <div class="swiper-button-next" slot="button-next"></div> </swiper>
说明:
carouselSwiperOptions是配置文件
v-if="carouselList.length" 添加这行是为了参数有值以后,才调用swiper,不然会有其他问题(比如展示的不是第一条数据)
// eslint-disable-next-line no-unused-vars let Vm = null
定义在最外面
// 轮播图swiper配置 carouselSwiperOptions: { slidesPerView: 1, spaceBetween: 30, loop: true, initialSlide: 0, // 自动播放 autoplay: { delay: 6000, stopOnLastSlide: false, disableOnInteraction: false }, // 滑动速度 speed: 1500, // horizontal direction: 'horizontal', observer: true, pagination: { el: '.swiper-pagination', clickable: true }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, on: { click: function () { // 上一页、下一页点击和点击图片都会触发click方法, // 不过上一页、下一页点击时,clickedIndex为undefined if (this.clickedIndex === undefined) { return } // realIndex当前点击的图在列表的index值 const realIndex = this.realIndex // 要在最外层定义Vm,直接使用this访问不到vue实例 Vm.swiperClick2(realIndex) } } },
在一次展示多个页面,而且循环滚动(loop: true) ,realIndex、activeIndex都会出现错乱,解决办法是在swiper-slide标签加上额外属性,点击的时候获取
例子:
加的是data-id属性 值为id
<swiper-slide v-for="item in specialColumnList" :key="item.id" :data-id="item.id" > <img class="carouselImg" :src="item.picPath" alt="carousel图片"> </swiper-slide>
点击的时候:
通过this.clickedSlide.attributes['data-id'].nodeValue获取
specialColumnSwiperOptions: { slidesPerView: 2, spaceBetween: 30, loop: true, initialSlide: 0, // 自动播放 autoplay: { delay: 6000, stopOnLastSlide: false, disableOnInteraction: false }, // autoplay: true, // 滑动速度 speed: 1500, // horizontal direction: 'horizontal', on: { click: function () { const id = this.clickedSlide.attributes['data-id'].nodeValue Vm.swiperClick1(id) } } }