chrisgrim's avatar

Issue getting vue Data into my toBlob function

Hi, I am trying to setup vue-cropperjs and I have it almost working except for uploading. I am trying to get the .file to upload. I have the following method

cropImage() {
          this.$refs.cropper.getCroppedCanvas().toBlob(function (blob) {
                    this.data = blob;
        });
        },

with this I get the error:

Cannot set property 'data' of undefined.

However if I do:

cropImage() {
          this.$refs.cropper.getCroppedCanvas().toBlob(function (blob) {
                    console.log(blob);
        });
        },

I get:

Blob {size: 2285576, type: "image/png"}. 

I thought the solution to this was just to do my axios submit inside of the toBlob function but my url is generated based off my Vue data as well.

How do I either set my Vue this.data to blob or how do I pass vue data into the blob function? Thanks!

0 likes
2 replies
ismaile's avatar
ismaile
Best Answer
Level 30

If you use ES6, the Javascript ES6 arrow function should do the trick and you should be able to access this:

cropImage() {
          this.$refs.cropper.getCroppedCanvas().toBlob(blob => {
                    this.data = blob;
        });
},

Otherwise, something like this should work:

cropImage() {
          var self = this;
          this.$refs.cropper.getCroppedCanvas().toBlob(function (blob) {
                    self.data = blob;
        });
},

For some explanation, you can check: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

chrisgrim's avatar

Amazing, thanks so much for the help and quick response!

1 like

Please or to participate in this conversation.