代码
export default class Random extends Vue {
// data
public nowIndex: number = -1;
public swiperOption: Object = {
slidesPerView: 6,
slidesPerGroup: 6,
loopFillGroupWithBlank: true,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev"
},
on: {
click: function(this: any): void {
nowIndex = this.clickedSlide.dataset.key;
}
}
};
}
问题:Click事件的this
直接指向Swiper
元素,我需要它来获取一个密钥来告诉我正在单击哪个密钥,并且我想将此密钥保存在vue数据中– nowIndex,但是我有一个错误提示“找不到名称'nowIndex'”
我做什么:我尝试在类中定义一个直接指向vue
的公共值this
,但它不起作用,错误还显示“ Cannot find name'vue'”
结束:我希望有人能看到这个并给我一个出路,非常想你TAT。
[nowIndex =
是一个错误,因为没有nowIndex
变量,并且nowIndex
类属性应始终称为this.nowIndex
。
请注意,事件处理程序中的此关键字始终指向Swiper实例
正如this answer所解释的,这是依赖于回调中的this
的库中的设计问题;函数不能同时使用组件this
和滑动器this
上下文。这可以通过使用self = this
hack来解决,也可以通过将函数签名绑定到其中一个上下文并使其接受另一个作为参数来解决。
这可以通过this answer中建议的辅助功能完成:
function contextWrapper(fn) {
const self = this;
return function (...args) {
return fn.call(self, this, ...args);
}
}
export default class Random extends Vue {
nowIndex: number = -1;
swiperOption?: any;
created() {
this.swiperOption = { /*...*/
on: {
click: contextWrapper((swiperInstance: any) => {
this.nowIndex = swiperInstance.clickedSlide.dataset.key;
})
}
};
}
}