TypeScript
1export default class Test extends Vue { 2 private clickEventClass: string = ""; 3 private clickEventfunctions: any[] = []; 4 5 mounted() { 6 this.addClickEvents(this.clickEventClass, this.clickEventfunctions); 7 } 8 9 @Watch(...........) 10 setClickEventsInfo() { 11 this.clickEventClass = "targetClass"; 12 this.clickEventfunctions.push(function (this: Test) { this.testFunc() }); 13 } 14 15 addClickEvents(targetClass: string, functions: any) { 16 console.log(functions); 17 const targetElement = document.getElementsByClassName(targetClass) as HTMLCollectionOf<HTMLElement>; 18 targetElement[0].onclick = () => { 19 while (functions.length > 0) { 20 functions.shift()(); 21 } 22 }; 23 } 24 25 testFunc() { 26 console.log("call test function"); 27 } 28 29}
typescriptでvue.jsを使い上記のようなクラスをvue内で使用しています。
目的としては配列内の関数を対象のcssクラスにクリックイベント登録したいと考えています。
実際にaddClickEventsで登録したのちにイベント発火させると下記のエラーとなってしまいます。
Uncaught TypeError: Cannot read property 'testFunc' of undefined
下記のようなコードで検証してみても同様のエラーが出ましてthisが参照できていないのではないかと推測しているのですが対処法がなかなか見当たらないのが現状です。
ちなみに何故かVSCodeではundefined部分が補完で出ます......
setClickEventsInfo() { this.clickEventClass = "targetClass"; this.clickEventfunctions.push(function (this: Test) { console.log(this.clickEventClass);}); }
アドバイスよろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。