[英]Use vue.js method in EventListener click in other method
我有一個vue.js腳本,它在方法中生成一個元素'lens'。 現在,我想添加一個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
問題:
如何在zoom方法中調用lightbox方法? 如果我將代碼從lightbox mehtod復制到zoom方法本身作為一個函數,我確實工作,但是因為lightbox方法也被其他元素調用,這將導致重復的代碼。
這是完整的代碼:
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); } } }); }
您必須this
附加到匿名函數,如下所示:
lens.addEventListener("click", function() { this.openLightbox(src) }.bind(this), false);
或者在語句之前定義別名,如下所示:
var self = this;
lens.addEventListener("click", function() { self.openLightbox(src) }, false);
否則, this
將不會引用您需要的父上下文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.