Tarounen
Tarounen

Reputation: 1159

this. undefined inside dropzone success callback vuejs2

I am using Dropzone.js with Vuejs2. The file upload is working fine however, inside the success callback function i cannot assign the response to an object of the parent.

Here is a sample of my implementation:

<script>
    import vueDropzone from "vue2-dropzone";

      export default {
        components: {
          vueDropzone
        },
        props: {
        },
        data: () => ({
            data: {
              name: ''
            },
            dropOptions: {
                url: "https://httpbin.org/post",
                maxFileSize: 10,
                autoProcessQueue: false,
                success: (file, response) => {
                if (response.message == "success"){
                  this.data.name = response.name;                
                  this.add();
                }
                else{
                  console.log('Error Uploading file');
                }
           }
       }),
     };
</script>

the error is:

Uncaught TypeError: Cannot set property 'name' of undefined

I tried the solutions found Here but its still not working.

Upvotes: 1

Views: 1038

Answers (2)

Vucko
Vucko

Reputation: 20834

Looking at the documentation, you're using it wrong.

dropOptions should only contain it's configuration, not the events.

You need to use the vue-2-dropzones events, in your case vdropzone-success(file, response), so:

<vue-dropzone
  ref="myVueDropzone"
  id="dropzone"
  :options="dropOptions"
  v-on:vdropzone-success="someSuccessMethod">
</vue-dropzone>

...
data() { /* ... */ },
methods: {
  someSuccessMethod(file, response) {
    // your logic
  }
}

Upvotes: 2

Enak
Enak

Reputation: 596

This simply does not work because this is binded to another object than you think. It is some default error from people switching or learning JavaScript.

dropOptions is an object. this in the success functions refers to the dropOptions object and not to the parent object of it.

So dropOptions has no field data hence is undefined and you can not access name.

See: access parent object in javascript

EDIT: For further investigation, please provide some code of what you have done with the link you posted. This seems to go to the right direction but from a simple "does not work", we can not tell you what else you need to keep in mind.

Upvotes: 0

Related Questions