Search code examples
javascriptvue.jsvuejs2callbackjspdf

How to pass value from function to variable in VueJs?


I am getting base64 of image url. When i pass the getImage function to savepdf funcion and try to store callback function base64_data in variable it throws an error of

Cannot set property 'base64logo' of undefined.

How to pass value from callback function to variable? Hope you understand my question.

          data() {
            return {
               base64logo: '',
            }
           },
            methods: {
            getImage(url, callback) {

                var img = new Image();
                img.crossOrigin = 'Anonymous';
                img.onload = function () {
                    var canvas = document.createElement('CANVAS');
                    console.log('canvas', canvas)
                    var ctx = canvas.getContext('2d');
                    var dataURL;
                    canvas.height = this.height;
                    canvas.width = this.width;
                    ctx.drawImage(this, 0, 0);
                    dataURL = canvas.toDataURL();
                    callback(dataURL);
                    canvas = null;
                };
                img.src = url;
            },

            savepdf() {

                this.getImage(this.clientDetails.company_logo, function (base64_data) {
                    console.log('base64_data', base64_data);
                    this.base64logo = base64_data; //Error HERE
                }); 
                    var doc = new jsPDF('p', 'pt', 'a4');
                    doc.setFontSize(9);
                    doc.addImage(this.base64logo, 'PNG', 150, 10, 40, 20); //Have to pass here.

              }
       }


Solution

  • You should use an arrow function ()=>{...} in order to access this component instance :

     this.getImage(this.clientDetails.company_logo,  (base64_data) =>{
                        console.log('base64_data', base64_data);
                        this.base64logo = base64_data; //Now you could access this
                    });
    

    or assign this to a global variable :

    let that=this
     this.getImage(this.clientDetails.company_logo,  function(base64_data){
                        console.log('base64_data', base64_data);
                        that.base64logo = base64_data; //Now you could access this
                    });