Vue使用vue-awesome-swiper实现轮播,loop模式下,前一个项目的点击事件失效

原因:因为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

官方介绍:

关键代码:

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

  },

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值