Sylvain
Sylvain

Reputation: 3070

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

Upvotes: 5

Views: 677

Answers (3)

Cong Nguyen
Cong Nguyen

Reputation: 3445

Use arrow function then you can access "this" of Vue instance inside success.

success: (filem response) => {
  this.photos = ..
}

Upvotes: 0

anchal20
anchal20

Reputation: 191

In your code there is a scoping issue with 'this' reference. I would suggest to use arrow function so that the scope of 'this' is that of the vue instance. The success function could 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 a part of ES2015. You would need babel to compile your code to a compatible version for all browsers. You can refer this site for compatibility issues

Hope this helps!

Upvotes: 1

m_callens
m_callens

Reputation: 6360

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

        }
    });
}

Upvotes: 6

Related Questions