vue2 vue-awesome-swiper loop 点击事件在某app里无效
使用this.$refs.mySwiper.swiper.activeIndex获取点击的那个slider的index。通过 属性data-click-flag绑定 index,在on 事件里响应 click 事件,一般来说就够了。之前同事已经改过一版,在微信及别的 app 里没问题了,但后面在某app上测试无效。给swiper绑定事件,其实这个问题很常见。
·
其实这个问题很常见。
之前同事已经改过一版,在微信及别的 app 里没问题了,但后面在某app上测试无效。
先看之前的方案:
<swiper :options="swiperOption" ref="mySwiper">
<div class="swiper-slide" v-for="(item, index) in imageList" :key="index">
<img :src="item.src"
data-click-flag="swiper-link" :data-click-index="index"/>
</div>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
export default {
data() {
return {
swiperOption: {
loop: true,
on: {
click: (v) => {
if (v.target.getAttribute('data-click-flag') === 'swiper-link') {
let index = v.target.getAttribute('data-click-index');
this.handleClick(index);
}
},
//处理设置时效显示轮播图不自动滚动问题
observerUpdate: () => {
this.$refs.mySwiper.swiper.slideTo(0)
}
}
}
}
}
}
通过 属性data-click-flag绑定 index,在on 事件里响应 click 事件,一般来说就够了。
可惜在某 app 上,死活点击无效,遂寻求其他方案,经过一番探索,找到了这个问答:
vue使用swiper的循环模式下,给每个滑块绑定事件 @click,复制的swiper-slide点击事件无效 - 编程宝库 (codebaoku.com)
给swiper绑定事件,
使用this.$refs.mySwiper.swiper.activeIndex获取点击的那个slider的index。<swiper :options="swiperOption" @click.native="doSome()" ref="mySwiper">
var index =(this.$refs.mySwiper.swiper.activeIndex - 1) % length;
经过测试发现上述方案可行,但不能直接用,修改后代码如下:
<swiper :options="swiperOption" ref="mySwiper" @click.native="handleSwiperClick()">
<div class="swiper-slide" v-for="(item, index) in imageList" :key="index">
<img :src="item.src"/>
</div>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
export default {
data() {
return {
swiperOption: {
loop: true,
}
}
},
methods: {
handleSwiperClick() {
let activeIndex = this.$refs.mySwiper.swiper.activeIndex - 1
if (activeIndex < 0) {
activeIndex += this.imageList.length
}
//index 为当前点击的 slide的index
var index = activeIndex % this.imageList.length;
}
}
}
重点:在 activeIndex 小于0的情况下,需要加上数组长度,才是真正的 index。
更多推荐
已为社区贡献1条内容
所有评论(0)