如何检测 Swiper 中幻灯片的点击?
How to detect a click on a slide in 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
是 class 成员?
this
上下文错误。在文档中它说:
Please note, that this keyword within event handler always points to Swiper instance
尝试不使用 mySwiper
,仅使用 this.clickedSlide
。
您可以毫不费力地将 function
更改为 arrow function
,您的函数范围将绑定到 this
。因此,您可以通过这种方式访问刷卡器!
另一种解决方案是使用 ViewChild 装饰器 @ViewChild('swiper-container')
我有一个 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
是 class 成员?
this
上下文错误。在文档中它说:
Please note, that this keyword within event handler always points to Swiper instance
尝试不使用 mySwiper
,仅使用 this.clickedSlide
。
您可以毫不费力地将 function
更改为 arrow function
,您的函数范围将绑定到 this
。因此,您可以通过这种方式访问刷卡器!
另一种解决方案是使用 ViewChild 装饰器 @ViewChild('swiper-container')