代码
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
,但是它不起作用,错误还显示“找不到名称'vue'”
结束: 我希望有人能看到这一点并给我出路,非常想你TAT。
答案 0 :(得分:0)
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;
})
}
};
}
}
或者通过使用骇客,在这种情况下this
的语义出现了错误:
export default class Random extends Vue {
nowIndex: number = -1;
swiperOption?: any;
created() {
const self = this;
this.swiperOption = { /*...*/
on: {
click(this: any) {
self.nowIndex = this.clickedSlide.dataset.key;
})
}
};
}
}