如何使用 Swiper.js 获取幻灯片的先前活动索引?

How do I get the previously active index of a slide using Swiper.js?

我可以使用 this.realIndex 获取当前幻灯片索引,如 documentation 所示,但 this.previousIndex 未生成先前活动幻灯片的 realIndex。相反,它提供了 activeIndex 的等效项,如滑块循环时所反映的那样。我怎样才能得到以前活动幻灯片的realIndex?这是 Swiper 中的错误吗?这可能需要进入本地存储吗?

我用这支笔将幻灯片索引记录到控制台。请注意 previousIndex 如何没有任何用处:https://codepen.io/thenomadicmann/pen/GRRPeWG?editors=1111

this.previousIndex - 1 应该给你之前活动幻灯片的 realIndex,一个问题是,如果 this.previousIndex - 1 值为 -1,这意味着没有以前活动的幻灯片,即刚刚初始化的滑动器,尚未完成滑动。这是因为 this.previousIndexinitializedactiveIndex 刷​​卡器初始化时。

@neevany 很接近,让我走上了正确的轨道。但是,对于希望使用 slideChange 事件在循环的 Swiper 中访问 previousIndex 的任何人,您不仅需要更正他描述的 -1 索引问题,还需要更正 swiper 循环时发生的双 slideChange 事件。代码如下:

// Have to use previousIndex in this fashion due to a bug in Swiper.js as of 11/21/19
let previousIndex = this.previousIndex - 1;
if ( previousIndex == -1 ) {
    previousIndex = 0;
} else if ( previousIndex == document.querySelectorAll( '.swiper-slide' ).length ) { // When swiper loops, slideChange gets fired twice and messes up animations. This prevents it from doing so.
    return;
}

对我来说,之前的答案没有帮助。 我创建了一个将 swiper.realIndex 存储在变量中的函数。然后我只是在 pagechange 上更新变量。

var previousIndex;
function getPreviousIndex(){
  previousIndex = swiper.realIndex;
};

getPreviousIndex();
swiper.on('slideChange', function () {
  getPreviousIndex();
});