You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中SwiperJS循环模式下slideChange事件重复触发问题求助

Swiper Loop模式下slideChange事件重复触发的解决方法

问题

开启loop: true的Swiper轮播,滑动到末尾继续滑动时,onSlideChange事件会触发两次,需实现无论是否完成循环,事件仅触发一次。

解决方案

利用Swiper的realIndex属性(对应真实slide的原始索引,排除loop模式下自动复制的slide),结合状态变量过滤重复触发:

<template>
  <swiper
    :navigation="true"
    :modules="modules"
    @slideChange="onSlideChange"
    loop
    class="mySwiper"
  >
    <swiper-slide>Slide 1</swiper-slide>
    <swiper-slide>Slide 2</swiper-slide>
    <swiper-slide>Slide 3</swiper-slide>
    <swiper-slide>Slide 4</swiper-slide>
    <swiper-slide>Slide 5</swiper-slide>
    <swiper-slide>Slide 6</swiper-slide>
    <swiper-slide>Slide 7</swiper-slide>
    <swiper-slide>Slide 8</swiper-slide>
    <swiper-slide>Slide 9</swiper-slide>
  </swiper>
</template>
<script setup>
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/css";
import "swiper/css/navigation";
import { Navigation } from "swiper";
import { ref } from 'vue';

// 记录上一次的真实slide索引
const lastRealIndex = ref(-1);

const onSlideChange = (swiper) => {
  const currentRealIndex = swiper.realIndex;
  // 仅当真实索引发生变化时执行业务逻辑
  if (currentRealIndex !== lastRealIndex.value) {
    lastRealIndex.value = currentRealIndex;
    console.log("事件触发", `当前真实slide索引:${currentRealIndex}`);
    // 在此处编写你的业务代码
  }
};

const modules = [Navigation];
</script>

原理说明

Loop模式下Swiper会自动复制首尾的slide以实现无缝循环效果,当滑动到末尾继续滑动时,会先切换到复制的slide触发一次slideChange,随后自动跳转到对应真实slide再触发一次事件。通过realIndex获取原始slide的索引,对比上一次记录的索引值,只有当索引真正变化时才执行逻辑,从而避免重复触发。

内容的提问来源于stack exchange,提问作者Exzia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:13:14