vue.jsthisuppy

How to access "this" from Uppy's callback event


I'm using the Uppy Vue component library, and following the docs, I've initialized Uppy by adding it as a computed property.

computed: {
    uppy: () => new Uppy({
        logger: Uppy.debugLogger
    }).use(AwsS3Multipart, {
        limit: 4,
        companionUrl: '/',
    }).on('complete', (result) => {
        this.testing = 'success';
        console.log('successful files:', result.successful);
        console.log('failed files:', result.failed);
    }),
}

I'm trying to update my Vue component's data now by using Uppy's complete event, but "this" is not defined. I'm not quite sure how to access "this" from here.

Any idea how to go about doing this?


Update

After posting this, I found a solution that works. I'm hesitant with this solution though as it seemed too easy.

If no one provides a better solution, I'll add this as the answer.

// Uppy Instance
uppy: function() {
    return new Uppy({
        logger: Uppy.debugLogger
    }).use(AwsS3Multipart, {
        limit: 4,
        companionUrl: '/',
    }).on('complete', (result) => {
        this.testing = 'success';
        console.log('successful files:', result.successful);
        console.log('failed files:', result.failed);
    })
},

Solution

  • By following the Uppy docs and instantiating the Uppy instance with an arrow function, this no longer seems to refer to the Vue. This makes it so that accessing this.method(), or this.variable, etc. no longer works.

    My solution was to change the Uppy instantiation from an arrow function to a regular function. I believe this causes this to refer to the global instance, but I don't have a solid understanding of this, so take what I say with a grain of salt.

    I changed this:

    computed: {
        uppy: () => new Uppy()
    }
    

    To this:

    computed: {
        uppy: function() { return new Uppy() }
    }