Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript & VueJS variable access

I'd like to access a VueJS variable from the success Dropzone event callback. All the code is OK, DropzoneJS & VueJS work fine together, but my variable photos is not accessible 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 to access VueJS components variables this way? Thanks

like image 750
Sylvain Avatar asked Mar 02 '17 14:03

Sylvain


1 Answers

The way you're doing it currently, you may have a scoping issue with the this reference.

I suggest reassigning this outside of the Dropzone instantiation and using that like so...

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

        }
    });
}
like image 104
m_callens Avatar answered Sep 24 '22 02:09

m_callens