1.安装

npm install swiper --save-dev

2.在组件中引用

import Swiper from "swiper"
import 'swiper/dist/css/swiper.css';

3.初始化swiper

new Swiper('.swiper-container', { 
	pagination: '.swiper-pagination',
	effect: 'coverflow',
	grabCursor: true,
	centeredSlides: true,
	slidesPerView: 'auto',
	loop:true,
	initialSlide : _this.activeIndex, 
	observer:true,//修改swiper自己或子元素时,自动初始化swiper
	observeParents:true,//修改swiper的父元素时,自动初始化swiper
	coverflow: {
		rotate: 50,
		stretch: 0,
		depth: 100,
		modifier: 1,
		slideShadows : true
	},
	on: {
		slideChangeTransitionEnd: function(){
			console.log(this.realIndex)
			_this.activeIndex = this.realIndex;
		},
	}

});

(1)loop=true 时,轮询播放,activeIndex获取不到真实的索引,应该使用realIndex获取。

(2)当数据更新时,更新swiper需要一些设置即可

initialSlide : 0, 
observer:true,//修改swiper自己或子元素时,自动初始化swiper
observeParents:true,//修改swiper的父元素时,自动初始化swiper

(3)因为数据是动态获取的,在数据请求之后再初始化swiper,这需要使用setTimeout做一下延迟

setTimeout(() => {
  new Swiper('.swiper-container', { 
	pagination: '.swiper-pagination',
	effect: 'coverflow',
	grabCursor: true,
	centeredSlides: true,
	slidesPerView: 'auto',
	loop:true,
	initialSlide : _this.activeIndex, 
	observer:true,//修改swiper自己或子元素时,自动初始化swiper
	observeParents:true,//修改swiper的父元素时,自动初始化swiper
	coverflow: {
		rotate: 50,
		stretch: 0,
		depth: 100,
		modifier: 1,
		slideShadows : true
	},
	on: {
		slideChangeTransitionEnd: function(){
			console.log(this.realIndex)
			_this.activeIndex = this.realIndex;
		},
	}

  });
},200)

官网地址:https://www.swiper.com.cn/

Logo

前往低代码交流专区

更多推荐