Javascript & VueJS variable access
Asked Answered
G

3

5

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

Gladden answered 2/3, 2017 at 14:35 Comment(0)
A
6

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

        }
    });
}
Ataliah answered 2/3, 2017 at 14:51 Comment(0)
M
1

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!

Monies answered 24/8, 2017 at 11:13 Comment(0)
H
0

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

success: (filem response) => {
  this.photos = ..
}
Hypochondriac answered 5/11, 2018 at 7:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.