我有一个 vue.js 脚本,它在一个方法中生成一个元素“镜头”。现在,我想添加一个 EventListener,它在单击镜头元素时调用另一个方法。
问题:
我尝试了两种不同的方法来添加侦听器。
1:有效lens.addEventListener("click", this.openLightbox(src));
但在页面加载时执行,而不是在点击时执行
2:lens.addEventListener("click", function() { this.openLightbox(src) }, false);
在点击而不是在有效载荷上执行,但抛出错误:Uncaught TypeError: this.openLightbox is not a function
The question:
How can I call the lightbox method in my zoom method? I does work if I copy the code from the lightbox mehtod into the zoom method itself as a function, however since the lightbox method is called by other elements as well that would lead to duplicate code.
Here is the full code:
initVue(target: string) : void {
this.vue = new Vue({
el: "#" + target,
store,
delimiters: vueDelimiters,
data: {
},
methods: {
openLightbox(src) {
console.log(src);
},
imageZoom(src) {
lens = document.createElement("DIV");
// works but is executed on pageload, not on click
lens.addEventListener("click", this.openLightbox(src));
// Is executed on click and not on payload, but throws error: Uncaught TypeError: this.openLightbox is not a function
lens.addEventListener("click", function() { this.openLightbox(src) }, false);
}
}
});
}Run Code Online (Sandbox Code Playgroud)
您必须this像这样附加到匿名函数:
lens.addEventListener("click", function() { this.openLightbox(src) }.bind(this), false);
Run Code Online (Sandbox Code Playgroud)
或者在语句之前定义一个别名,如下所示:
var self = this;
lens.addEventListener("click", function() { self.openLightbox(src) }, false);
Run Code Online (Sandbox Code Playgroud)
否则,this将不会引用您需要的父上下文。
| 归档时间: |
|
| 查看次数: |
1772 次 |
| 最近记录: |