Access to Javascript and VueJS Variable

I want to access the VueJS variable from the success callback of the Dropzone success event. All code is fine, DropzoneJS and VueJS work fine together, but my photos variable is not available in the success callback.

Here is a simple implementation of my script:

 <script> import Dropzone from 'dropzone'; export default { data() { return { photos: [] }; }, ready() { Dropzone.autoDiscover = false; new Dropzone('form#upload-form', { url: '...', success: function(file, response) { this.photos = response.data.photos; // this.photos is not accessible here } }); } } </script> 

Is there a best practice for accessing VueJS component variables this way? Thanks

+5
source share
2 answers

As you do this now, you may have a problem with this .

I suggest reassigning this outside of the Dropzone instance and using it like this ...

 ready() { Dropzone.autoDiscover = false; const self = this; new Dropzone('form#upload-form', { url: '...', success: function(file, response) { self.photos = response.data.photos; // this.photos is not accessible here } }); } 
+5
source

Your code has a problem specifying 'this'. I would suggest using the arrow function so that the 'this' region is that of the vue instance. The success function can be written something like this: -

 ready() { Dropzone.autoDiscover = false; new Dropzone('form#upload-form', { url: '...', success: (file, response) => { this.photos = response.data.photos; } }); } 

The arrow function is part of ES2015. You will need babel to compile your code into a compatible version for all browsers. You can link to this site for compatibility issues.

Hope this helps!

+1
source

Source: https://habr.com/ru/post/1264945/


All Articles