详解swiper在vue中的应用(以3.0为例)

2020-06-13 10:30:37易采站长站整理

一、使用方法

官网地址

参考此文章(点击我)

二、常见情况

图片需要动态获取时

待数据加载成功且渲染完毕后,进行节点初始化。例:


axios.post(‘接口地址', 参数).then(response => {
this.pages = response.data; //pages 渲染数据的数组
this.$nextTick(() => { //渲染结束
// mySwiper 里面的属性按需配置,详情见官网
let mySwiper = new Swiper(".swiper-container", {
initialSlide :0,//默认播放(值为图片下标)
loop: false,//不循环
speed: 600, //切换速度
paginationClickable: true, //点击小点可以切换
});
});
});

当有 3 组图片需要依次播放时(多组以此类推)

情景:第 2 组图片滑动最后一张时,需要加载第 3 组图片;第 2 组图片滑动第一张时,需要加载第 1 组图片。

方法:在初始化的时候,配置回调函数onTouchStart(开始滑动的X轴值)和 onTouchEnd(结束滑动的X轴值)。用差值来判断是往前滑还是往后划。


this.$nextTick(() => {
let mySwiper = new Swiper(".swiper-container", {
observer: true, //修改swiper自己或子元素时,自动初始化swiper
observeParents: true, //修改swiper的父元素时,自动初始化swiper
onTouchStart: function(swiper) {
this.positionStart = swiper.getWrapperTranslate();
},
onTouchEnd: function(swiper) {
this.positionEnd = swiper.getWrapperTranslate();
if (this.positionStart > this.positionEnd && this.pages.length - 1 == this.mySwiper.activeIndex) {
//向后滑,加载后一组图片
} else if (mySwiper.activeIndex == 0 && this.positionStart < this.positionEnd) {
//向前划,加载前一组图片
}
}
});
});

这时,图片已经加载了另外一组图片,但是各组图片之间没有连贯起来,这就需要用到 slideTo方法去跳转(若加载第 3 组,则跳转到下标第 0 个;若加载第 1 组,则跳转到下标第 图片个数-1 个)。


mySwiper.slideTo('要跳转的图片下标', 10, false) // 10表示跳转速度;false 代表是否触发回到函数

数据方法配置


export default {
name: '',
data() {
return {
swiperOption: {
// NotNextTick is a component's own property, and if notNextTick is set to true, the component will not instantiate the swiper through NextTick, which means you can get the swiper object the first time (if you need to use the get swiper object to do what Things, then this property must be true)
// notNextTick是一个组件自有属性,如果notNextTick设置为true,组件则不会通过NextTick来实例化swiper,也就意味着你可以在第一时间获取到swiper对象,假如你需要刚加载遍使用获取swiper对象来做什么事,那么这个属性一定要是true