vue/typescript/vue-awesome-swiper 中的 `this` 方向 [英] `this` direction in vue / typescript / vue-awesome-swiper
问题描述
代码
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;
}
}
};
}
问题:单击事件的 this
直接指向 Swiper
元素,我需要它来获取一个键来告诉我正在单击哪个键,我想将此键保存在 vue 数据中——-- nowIndex ,但我有一个错误提示 找不到名称 'nowIndex'"
Question:
Click event's this
direct to the Swiper
element , I need it to get a key to tell me which one is being clicked , and I want save this key in vue data ---- nowIndex , but I had a error says "Cannot find name 'nowIndex'"
我做什么:我尝试在类中定义一个直接指向 this
的公共值 vue
,但它不起作用,错误还说 找不到名称 'vue'"
What I do:
I try defined a public value vue
direct to this
in the class , but it does not work , the error also says "Cannot find name 'vue'"
结束:我希望有人能看到这个并给我一条出路,觉得你很TAT.
End: I hope someone can see this and give me a way out , think you very much TAT .
推荐答案
nowIndex =
是一个错误,因为没有 nowIndex
变量,而 nowIndex
> 类属性应始终称为 this.nowIndex
.
nowIndex =
is a mistake because there's no nowIndex
variable, and nowIndex
class property should always be referred as this.nowIndex
.
文档 指出:
请注意,事件处理程序中的 this 关键字始终指向 Swiper 实例
Please note, that this keyword within event handler always points to Swiper instance
正如 this answer 所解释的,这是依赖于 this
的库中的设计问题在回调中;一个函数不能同时使用组件 this
和 swiper this
上下文.这可以通过使用 self = this
hack 或通过将函数签名绑定到这些上下文之一并使其接受另一个作为参数来解决.
As this answer explains, this is design problem in a library that relies on this
in callbacks; a function cannot use component this
and swiper this
contexts at the same time. This can be solved either by using self = this
hack, or by binding function signature to one of these contexts and making it accept another one as a parameter.
这可以通过这个答案中的建议使用辅助函数来完成:
This can be done with helper function as suggested in 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;
})
}
};
}
}
或者通过使用 hack,在这种情况下 this
语义出错了:
Or by using a hack, in this case this
semantics goes wrong:
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;
})
}
};
}
}
这篇关于vue/typescript/vue-awesome-swiper 中的 `this` 方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!