原因:因为swiper的无限轮播时会自动复制第一个和最后一个页面进行轮播。但由于只复制页面没有复制点击事件,此时我们用vue写的点击事件在页面循环一周回来遇到复制的页面时,点击事件就会失效。
解决办法:在swiper的回调函数中直接操作DOM
click和tap事件的区别
click事件
click事件是pc端的单机事件,但是当这个事件在移动端实现的时候,会出现延迟300ms的现象,所以移动端一般用tap来代替click。
tap事件
tap可以减少click在移动端的延迟,提高了性能。
案例:
<template>
<div>
<div class="main-content">
<!-- 轮播图 -->
<div>
<swiper :options="swiperOption">
<swiper-slide v-for="item in dataList" :key="item.id">
<img
:src="item.imgUrl"
@tap="openDetail(item)"
/>
<div class="swiper-content">{{item.name}}</div>
</swiper-slide>
</swiper>
</div>
</div>
</div>
</template>
<script>
import { swiper, swiperSlide } from 'vue-awesome-swiper'
let vm = null
export default {
components: {
swiper,
swiperSlide
},
data() {
return {
dataList:[],//数据
swiperIndex: null,
// 配置属性
swiperOption: {
direction: 'horizontal', // 滑动的方向(水平方向)
loop: true, // 是否循环
slidesPerView: 'auto', // 设置可视区一共显示几张图片,设置auto,设置auto为自适应;
centeredSlides: true, // 设置为true时,带有active-slide类名的图片会居中
spaceBetween: -7, // 每张图片之间的间隔
on: {
click: function (e) {
console.log(this)
vm.swiperIndex = this.realIndex
let url = vm.dataList[vm.swiperIndex].Url
vm.openDetail(url)
}
}
},
}
},
created() {
vm = this
},
methods: {
openDetail(url) {
if (url === '') {
alert('暂无链接')
} else {
location.href = url
}
},
}
}
</script>
这里我们打印拿到swiper
官方介绍:![](https://img-blog.csdnimg.cn/5005dce5341b4716889f8e33dd5f0e7c.png)
关键代码:
1 创建vm
let vm = null
2 配置
使轮播图的标识index与当前vue实例的swiperIndex标识一致,这样就可以使点击事件生效
轮播图配置属性里
on: {
click: function (e) {
console.log(this)
vm.swiperIndex = this.realIndex
let url = vm.cloudList[vm.swiperIndex].wxArticleUrl
vm.openDetail(url)
}
}
data:
swiperIndex: null,
3 使vm指向当前vue实例
created() {
vm = this
},