Skip to content Skip to sidebar Skip to footer

State Not Assigned Inside Onload Function

I'm trying to assign the data url of an image to a state but it isn't being assigned to the state. First I convert a blob url to data url and then assign it to a state in vuejs, ho

Solution 1:

this inside the onload callback doesn't refer to the vue instance , to make it refer you should assign this to a global variable then use that variable inside the callback :

upload() {
      this.imgSrc = this.value;
      let img = new Image();
      img.src = this.value;
     let vm=this;
      img.onload = function () {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        canvas.getContext('2d').drawImage(img, 0, 0);
        const dataURI = canvas.toDataURL();
        vm.imgSrc = dataURI;
        console.log('imgSrc inside', vm.imgSrc);
      };
     //any code here will be ran before the callback 
    },

Post a Comment for "State Not Assigned Inside Onload Function"