【问题标题】:How to detect a click on a slide in Swiper?如何在 Swiper 中检测对幻灯片的点击?
【发布时间】:2018-07-24 14:40:43
【问题描述】:

我有一个 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 是类成员?

【问题讨论】:

    标签: angular typescript ionic3 swiper


    【解决方案1】:

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

    请注意,事件处理程序中的这个关键字总是指向 Swiper 实例

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

    【讨论】:

    • 正如文档所说,我知道我们需要 this 前缀才能访问 swiper 属性(如 clickedSlide)。其实不带前缀的,经过测试,是mySwiper is undefined
    • 我搞混了,因为 this 指向 Swiper 实例,所以不需要 mySwiper,我编辑了答案,你可以试试吗?
    【解决方案2】:

    您可以毫不费力地将function 更改为arrow function,并且您的函数范围将绑定到this。因此,您可以通过这种方式访问​​ swiper!

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-06
      • 2019-09-29
      • 2019-09-28
      • 1970-01-01
      • 2020-03-18
      • 2022-07-19
      • 2019-09-06
      • 2022-12-21
      相关资源
      最近更新 更多