「Vue.js」でdata値を参照するときに「this.」は欠かせませんよね。
しかし、クロージャの中から「this.OOO」を使用しても使えません。
クロージャとは、入れ子の関数みたいなもの?です。
コンソールでthisの値を確認すると
メソッドを呼び出してしまいます。
Vue.jsの「this」として挙動しなくなります。
var up_image = new Image(); const reader = new FileReader(); reader.onload = (e) => { this.file_type = this.file.type; this.uploadedImage = e.target.result; up_image.src = reader.result; up_image.onload = function(){ this.upload_width = up_image.naturalWidth; this.upload_height = up_image.naturalHeight; }; } reader.readAsDataURL(this.file); },上記はNGな例です。
upload_width、upload_heightはVueのdataへ値の代入をしています。
しかし、クロージャ内なのでthisの値は期待する値ではありません。
解決策としては、
var up_image = new Image(); const reader = new FileReader(); reader.onload = (e) => { this.file_type = this.file.type; this.uploadedImage = e.target.result; up_image.src = reader.result; up_image.onload = function(){ _this.upload_width = up_image.naturalWidth; _this.upload_height = up_image.naturalHeight; }; const _this = this; } reader.readAsDataURL(this.file); },このように関数の外で定義された変数を
関数内で使えば解決できます。
この場合だと、
関数の外で _thisに thisを代入しています。
そして関数内でthis代わりに_thisを使用しています。
こうすることでvueのdataの値に代入することができます!
かなり説明が分かりにくくなってしまいました、、が以上です。
最後まで読んでいただきありがとうございました。
スポンサーリンク
コメント