如何在Swiper中检测到对幻灯片的单击?

时间:2018-07-24 14:40:44

标签: angular typescript ionic3 swiper

我有一个Angular 2组件,其中包含来自Swiper包的滑块。我想知道我点击了哪张幻灯片(它的索引)。尝试遵循Swiper documentation,我有这个问题:

import { Component, AfterViewInit } from "@angular/core";
import Swiper from "swiper";

@Component({
    selector: "challenges",
    templateUrl: "challenges.component.html"
})
export class ChallengesComponent implements AfterViewInit {
    public mySwiper: Swiper;
    public slides = [
        "https://via.placeholder.com/300x200/",
        "https://via.placeholder.com/300x200/",
        "https://via.placeholder.com/300x200/"
    ];

    constructor() { }

    public ngAfterViewInit() {
        this.mySwiper = new Swiper(".swiper-container", {
            slidesPerView: 3,
            spaceBetween: 30,
            pagination: {
                el: ".swiper-pagination",
                type: "bullets",
                clickable: true
            },
            on: {
                click: function(){
                    console.log(this.mySwiper.clickedSlide);
                }
        }
        });
    }
}

问题是,如果我单击一张幻灯片,则会出现此错误this.mySwiper is undefined。为什么this.mySwiper是班级成员?

2 个答案:

答案 0 :(得分:2)

this的上下文错误。在文档中说:

  

请注意,事件处理程序中的此关键字始终指向Swiper实例

尝试不使用mySwiper,仅使用this.clickedSlide

答案 1 :(得分:0)

您无需费力即可将find更改为function,并且您的功能范围将绑定到arrow function。这样您就可以通过这种方式访问​​swiper!

另一种解决方案是使用ViewChild装饰器@ViewChild('swiper-container')