What is the best way to transfer a value from a function to a variable in VueJs?

Currently, I am receiving the base64 of an image URL. When passing the getImage function to the savepdf function and attempting to store the callback function's base64_data in a variable, an error is thrown:

An error occurs - Cannot set property 'base64logo' of undefined.

How can I successfully pass the value from the callback function to the variable? I hope my question is clear.

          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; //The Error Occurs Here
                }); 
                    var doc = new jsPDF('p', 'pt', 'a4');
                    doc.setFontSize(9);
                    doc.addImage(this.base64logo, 'PNG', 150, 10, 40, 20); //Should be passed here.

              }
       }

Answer №1

To effectively access the component instance, it is recommended to utilize an arrow function like ()=>{...}:

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

Alternatively, you can store this in 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
                });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with the functionality of the cascading menu?

I am having trouble with a drop-down menu. The first level works fine, but I can't seem to get the second level of the menu to display. Appreciate any help you can offer. Thank you. javascript <script type="text/javascript"> $(document).ready( ...

Revamping this snippet - JavaScript with NodeJs

Currently working on a basic CRUD application, encountering an issue with obtaining the auto-incrementing value for the latest account in MongoDB. To provide more context, I've included the snippet below to achieve the following: 1) Conduct validati ...

Execute a query to retrieve a list of names and convert it to JSON using Unicode encoding in

Just starting out with Laravel and I'm trying to figure out how to execute some queries Not talking about the usual select statements... I need to run this specific query: SET NAMES 'utf8' First question, here we go: I have Hebrew ...

Sending a PHP variable to a JavaScript function

When attempting to pass a value to a JavaScript function by clicking a link, I encountered an error message: Uncaught SyntaxError: Unexpected identifier The following is the code snippet: <?php include_once("php_includes/check_login_status.php") ...

Validating fields using JavaScript and HTML

I'm having an issue with the code below because it only allows me to log in with the user and password from the last position of the arrays. I want it to let me login with each user and their corresponding password, for example, user at position 1 wit ...

The sequence of error middleware in Express4

Encountered a series of code execution that seemed unusual. Here's the code snippet: server.js const Actions_Single_PVC = require('./routes/Actions_single_PVC.js'); app.use('/Actions_single_PVC', Actions_Single_PVC); app.use((e ...

Laravel mix is compiling the Vuetify styles in the sass file and generating an empty CSS file

I am having trouble compiling vuetify 2.0.0-beta.9 SASS using laravel mix. When I compile the styles.sass file, it generates an empty css file. How can I resolve this issue? Following the documentation (), I started by running: $ npm install sass sass-lo ...

Having trouble with npm global installation? Encountering the error message "Error: EACCES: permission denied

As the administrator of my MacBook, I am facing an issue while trying to run a npm command in my Django project. It is refusing to run due to missing permissions. (venv) jonas@Air-von-Jonas salaryx % npm install -g sass npm ERR! code EACCES npm ERR! syscal ...

Node-static is reporting that the localhost page cannot be located

I am currently attempting to serve static files using node-static. My plan is to eventually run this as a Windows service using nssm. I have successfully executed this process in the past, however for some reason it is not working now. Here is the code sn ...

Tips for adjusting the button color in Material UI by utilizing the ":active" pseudo-class

In the project I am currently working on, I am incorporating Material UI. One of the tasks I need to complete is changing the active state of a button. I have implemented both hover and active states from Material UI in my code: const useStyles = makeStyle ...

How to set a default value in AngularJS ng-model using the value from another ng-model

One of the challenges I'm facing is transferring a value set by the user in an ng-model from one form field to another ng-model as the initial value within the same form. For example, I want the ng-init value of myModel.fieldB to be the val ...

Transferring a JavaScript element's ID to PHP

Recently, I came across a JavaScript function that automatically updates the date and time for me. I found the script on this URL: http://jsfiddle.net/pLsgJ/1/ setInterval(function() { var currentTime = new Date ( ); var currentHours = curren ...

Converting a numerical value starting with zero into a string while retaining the leading zero

I am facing an issue with my JavaScript code that retrieves GPS location from a browser. Due to the limitation of writing coordinates to an SQL database directly from JavaScript, I have resorted to sending it via PHP by utilizing the controller "site" and ...

Is there a way to adjust the font size in Javascript/Html without changing the color?

I have a code snippet that creates a button to increment a variable, and I want to change the font size of the displayed variable. This code is for a game akin to cookie clicker. <div class="game-object"> <script type="text/javascript>"; var c ...

"Dilemma: Why won't the AJAX form post load inside the

Apologies for the simple question, but I'm experiencing an issue where nothing happens when the button is pressed. Any assistance would be greatly appreciated. AJAX $(document).on("ready", function(){ //Form action $("#wbForm").on("submit", function( ...

Guide to showing content in Vue based on the condition that a Firestore field matches a certain string value

The string field reviewPrivacy in the review collection of the Firestore database is populated by a user's selection from a Vue form (radio buttons) with three options, one of which is keepFullyPrivate. I want to only show the message <h2>The r ...

Check a field for validation only when it is visible on the screen

One challenge I'm facing is with an asp.net webform. I have a hidden field that is only displayed when a user selects a radio button. The catch is, this hidden field needs to be mandatory only when it's visible; otherwise, I don't want it to ...

unable to locate public folder in express.js

I recently created a basic server using Node.js with Express, and configured the public folder to serve static files. Within my main index.js file, I included the following code: const express = require('express'); const app = express(); const h ...

Issue with Nuxt 3 and .nojekyll file not being effective on Github Pages

I am facing some challenges while attempting to deploy my nuxt project on a github page. I have included the .nojekyll file in the public folder, but even after running generate, files with "_" are still showing up under public/static. https://i.sstatic ...

Deactivate the underscore and include the fiscal year in AngularJS

I am currently faced with a scenario where the back end is returning the value as follows: 123222_D1.123 However, I need to display the date from the database (12-Jun-2020) as 2020-D1.123 in a drop-down menu. Currently, I am displaying the above value i ...