• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

解决vue使用swiper 同时设置loop和slidesPerView时 点击事件失效问题

武飞扬头像
云小黛
帮助1


前言

在实际运用swiper轮播图插件时,有时会出现需要同时使用 loop: trueslidesPerView: ‘auto’ 两种属性的情况,前者代表开启循环模式,后者代表slider容器能够同时显示的slides数量(carousel模式)。

此时,会出现点击事件失效问题,主要原因是 loop: true 会产生复制的slide,而在“假的”slide上正常绑定的点击事件无法生效。


一、swiper - loop原理

学新通参考链接:Swiper中文网 - loop

二、swiper - slidesPerView属性解释

学新通

参考链接:Swiper中文网 - carousel

三、解决方法

1. HTML部分

<div class="carousel">
	<swiper ref="noticeSwiper" :options="swiperOptions">
		<swiper-slide v-for="(item, i) in list.notice" :key="i">
			<div class="title">
				<span>{{ item.title }}</span>
			</div>
			<span>{{ item.createdTime }}</span>
		</swiper-slide>
	</swiper>
</div>

2. data部分

let vm = null
export default {
	// etc.
}
data() {
	return {
		list: {
			notice: [], // 列表
		}
		swiperOptions: {
			direction: 'vertical',
	        height: 52,
	        slidesPerView: 2,
	        loopedSlides: 4, // 在loop模式下使用slidesPerView,还需使用该参数设置所要用到的loop个数(一般设置大于可视slide个数2个即可)
	        observer: true, // 改变swiper样式时,自动初始化swiper
	        observeParents: true, // 监测swiper父元素,如果有变化则初始化swiper
	        autoplay: {
	        	delay: 3000,
	        	disableOnInteraction: false,
	        },
	        loop: true,
	        on: {
				tap: function () {
					// 这里有坑,需要注意的是:
					// this 指向的是 swpier 实例,而不是当前的 vue, 因此借助 vm,来调用 methods 里的方法
					let initIndex = this.clickedIndex - this.activeIndex   this.realIndex
					let index = initIndex === vm.list.notice.length ? 0 : initIndex
					vm.toNoticeDetail(index)
				},
	        },
		}
	}
}
学新通
computed: {
    noticeSwiper() {
      	return this.$refs.noticeSwiper.$swiper
    },
}

3. 方法部分

methods: {
	toNoticeDetail(index) {
		// 示例:查看详情
		this.$router.push({
			path: '/contentDetail',
			query: {
				id: this.list.notice[index].id, // 通过index获取数据
			},
		})
	},
}
created () {
 	vm = this
}

总结

在vue中使用swiper,同时设置loop和slidesPerView时,解决点击事件失效问题的关键,在于获取真实的 index 以及设置 loopedSlides 属性。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbehhg
系列文章
更多 icon
同类精品
更多 icon
继续加载