<swiper class="swiper" :current="curDot" @change="swiperChange">
<swiper-item v-for="(item, index) in list" :key="index">
<view class="swiper-item uni-bg-red">{{item}}</view>
</swiper-item>
</swiper>
首先个swiper绑定 :current="curDot" @change="swiperChange"这两个属性
current表示当前所在滑块的 index
current 改变时会触发 change 事件,event.detail = {current: current, source: source}
然后在data中初始curDot: 0,再添加swierChange事件
swiperChange(e) {
this.curDot = e.detail.current;
},
然后再给页面添加左右按钮
<view class="left-right">
<view class="left-back" @click.stop="leftImg">
<text class="icon-back"></text>
</view>
<view class="right-forword" @click.stop="rightImg">
<text class="icon-right"></text>
</view>
</view>
然后在添加前进后退事件
leftImg(){
let num = this.list.length - 1
if (this.curDot <= 0) {
this.curDot = num
} else {
this.curDot--
}
},
rightImg(){
let num = this.list.length - 1
if (this.curDot >= num) {
this.curDot = 0
} else {
this.curDot++
}
}
这样就完成了。
方法完善
上述方法在swiper中没有添加 :circular='true' 属性,造成的结果是在第一张图片向左切换到最后一张图片,或者最后一张图片向右切换到第一张图片时。图片向相反方向滑动了整个数组的长度,实际体验并不好。
如果直接添加:circular='true'属性,会造成除第一张和第二张外,其余图片向左切换时,会向右滑动一个数组长度。
最终解决方法,动态控制 circular 的属性值
<swiper class="swiper" :current="curDot" @change="swiperChange" :circular='circular'>
<swiper-item v-for="(item, index) in list" :key="index">
<view class="swiper-item uni-bg-red">{{item}}</view>
</swiper-item>
</swiper>
在data中初始化 circular: true,
左右切换方法中动态修改circular的值,说明:向左切换时,circular设为false,当第一张切最后一张时设为true。
leftImg(){
this.circular = false
let num = this.list.length - 1
if (this.curDot <= 0) {
this.circular = true
this.curDot = num
} else {
this.curDot--
}
},
rightImg(){
this.circular = true
let num = this.list.length - 1
if (this.curDot >= num) {
this.curDot = 0
} else {
this.curDot++
}
}