vue使用swiper的时候第二轮事件不会触发问题

Yonina ·
更新时间:2024-09-20
· 1236 次阅读

目录

使用swiper的时候第二轮事件不会触发

解决这种有两种方法

swiper点击事件无效的问题

现象

分析

原因

解决方法

使用swiper的时候第二轮事件不会触发

首先说明导致这样的结果的原因:官方解释是轮播在循环轮播的时候他是前面复制一份后面复制一份,这样看起来就是无缝滚动,但是在复制的时候不会复制事件,所以会有事件不会触发

解决这种有两种方法

第一种loop为false,这样没有复制元素自然也不存在复制事件这一说法

第二种重新写options

第一步定义ref跟重新定义options

data里面是不需要的

计算属性里面写个事件swiper事件是原swiper自带的在点击的时候computed会自动监听跟watch差不多(缓存),然后让其指向我们当前使用的swiper让其有原生的方法,swiper里面有个on属性 里面是绑定事件让其执行swiper方法,返回当前dom,常用的获取id的方式

clickedSlide当前轮播dom

activeIndexloop模式下注意该值会被加上复制的slide数

realIndex与activeIndex不同的是,在loop模式下不会将复制的块的数量计算在内。

常用获取的方法 其余看文档

切记:最后要将optins返回 然后绑定值options

computed: { swiper() { return this.$refs.mySwiper.swiper }, swiperOption() { let option = { slidesPerView: 5, // height: 'auto', autoplay: { delay: 3000, stopOnLastSlide: false, /* 触摸滑动后是否继续轮播 */ disableOnInteraction: false }, spaceBetween: 1, // observer: true,//修改swiper自己或子元素时,自动初始化swiper // observeParents: true,//修改swiper的父元素时,自动初始化swiper direction: "vertical", //设置垂直滚动方向 speed: 800,//滚动速度 grabCursor: true, loop: true,//循环滚动 on: { click: (swiper) => { console.log(this.date[this.swiper.clickedSlide.getAttribute('data-index')].userId); this.$store.commit("showDialog5", this.date[this.swiper.clickedSlide.getAttribute('data-index')].userId); }, }, } return option } },

swiper点击事件无效的问题 现象

添加在swiper-slide里面的点击事件有时能点击有时不能点击

分析

只有在设置了loop:true的情况下才会出现这个问题

原因

swiper通过复制dom节点来实现无限滚动,但没有复制元素上绑定的事件

解决方法

在轮播配置里面定义事件,即options里面,这样的话可以解决不能点击的问题

但有时候需求会复杂一点,比如需要点击轮播图里面特定元素,做出不同的响应事件,这时候就需要做一些另外的工作来辅助完成。

首先要将 preventLinksPropagation设置成false,防止冒泡。

然后通过判断点击的元素的类名来响应不同的事件,这个时候,我们可能需要给事件传递参数,但是需要传递的参数是通过v-for生成的,如何传递,这里我的做法是将参数放到元素的自定义属性里面 然后再获取自定义属性。

<swiper ref="mySwiper" :options="swiperOption"> swiperOption: {         spaceBetween: 10,         loop: true,         slidesPerView: 'auto',         loopedSlides: 3,         slidesOffsetBefore: (document.body.clientWidth * 0.2) / 2,         preventLinksPropagation: false,         on: {           click: (v) => {             const item = {               a: v.target.getAttribute('data-a'),               b: v.target.getAttribute('data-b'),               c: v.target.getAttribute('data-c')             }             switch (v.target.className) {               case 'a':                 this.handlegg(0)                 break               case 'b':                 this.handlegg(1, item)                 break               case 'c':                 this.handlegg(2, item)                 break             }           }         }       }

轮播图里面某元素

<div v-else class="xxx">  <div      class="c"     :data-a="item.a"      :data-b="item.b"      :data-c="item.c"     ></div>   <div>立即开通</div> </div>

问题解决。 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。



VUE 事件 swiper

需要 登录 后方可回复, 如果你还没有账号请 注册新账号