Refactor Print Preview Graph Display Issue within Nested Vue Component

I seem to be having trouble accessing this function properly due to an error. I am unsure of how to troubleshoot this issue and determine the correct solution. Any guidance would be greatly appreciated.

The component PerformanceDonut.vue is located within the Page.vue file.

Here's the code snippet from PerformanceDonut.vue:

// ...
methods: {
    drawGraph() {
        this.chart = new CanvasJS.Chart(this.chartName, this.chartOptions);
        this.chart.render();
         console.log('Donut drawn')
    }
},
mounted() {
    this.drawGraph();
    // The function gets executed here

    // Re-draw graph for print preview
    window.matchMedia('print').addListener(function(mql) {
        if (mql.matches) {
            this.drawGraph();
            // Error occurs here
        }
    });
}

Console displays the following error message:

Uncaught TypeError: this.drawGraph is not a function

Answer №1

To utilize a arrow function for utilizing this as the reference of a Vue component:

window.matchMedia('print').addListener( mql => {
    if (mql.matches) {
        this.drawGraph();
    }
});

Answer №2

To ensure proper access in the callback due to the change in execution context, assign this to a global variable named vm before using it:

   mounted() {
            this.drawGraph();
            // The function is executed here

            let vm=this;
            window.matchMedia('print').addListener(function(mql) {
                if (mql.matches) {
                    vm.drawGraph();

                }
            });

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

Unlocking the secret to accessing state in a JavaScript file using VUEX

Can anyone help me figure out why I can't access the currentUser property from the state in my vuex store's user.js file? I'm trying to use it in auth.js, but when I write: store.state.currentUser.uid === ... This is the error message I&apo ...

Tips for acquiring the newest router in an angular environment

Is there a way to retrieve and store the URL of the latest router that the user has visited in local storage? Any suggestions would be greatly appreciated. Thank you! ...

Ensuring that an md-radio-group is a required field in Angular Material

Currently, I am working on a project using Angular Material where I need to enforce a required radio group. This means that the user must select a radio button before being able to submit the form. The form should be considered invalid if no radio button i ...

Provide a response containing JSON data extracted from an HTML file

I am looking for a way to create a simple REST API using a hosting site that only allows hosting of HTML files along with JavaScript files. I want to be able to send POST/GET requests and receive JSON data in response. For instance, when making a GET requ ...

What could be causing the "Circular structure to JSON" error in Node.js when executing a MySQL query?

Currently, I am working on executing a MySQL query to retrieve all the data from a table named LOGIN. If you navigate to https://localhost:2000/select, and provide the parameter in the req.body as table_name with the value set as login. When making t ...

Creating a VSCode extension using Vue: Step-by-step guide

I'm looking to develop a VSCode extension with Vue utilizing the VSCode webview. However, when attempting to import the compiled index.html into my extension, I consistently receive a prompt to enable JavaScript. Is there a solution for integrating Vu ...

Comparing Embedded and Linked JS/CSS

In my experience, I understand the advantages of using linked CSS over embedded and inline styles for better maintainability and modularity. However, I have come across information suggesting that in certain mobile web development applications, it may be m ...

Verify if a user in discord.js has the necessary permissions

I need a special command that is restricted to users with the ban permission current code: if(msg.member.guild.me.hasPermission('BAN_MEMBERS')) { msg.channel.send("hi") } else { msg.channel.send("You do not have ...

Error with JavaScript callback functions

After creating a POST route, I encountered unexpected behavior in the code below. The message variable does not display the expected output. app.post("/", function (req, res, error) { var message = ""; tableSvc.createTable("tableName", function (error ...

Struggling to generate a fresh invoice in my project using React.js

I am fairly new to working with React and could really benefit from some assistance in understanding how to implement a new invoice feature within my current project. The Challenge: At present, I can easily create a new invoice as showcased in the images ...

Using jQuery to add the name of a file to FormData and fetching it in a PHP script

I've been working on a JS code snippet dedicated to uploading images based on their file paths: var data = new FormData(); data.append('fileName', fileName); data.append('file', file); $.ajax({ url : dbPath + "upload-file.php" ...

Specialized selection option with disabled function

Looking for assistance with a script to create a custom select box. I have UL and LI elements overlapping a select element, but I want to prevent the UL LI from opening when the select has a "disabled" attribute. Can anyone provide guidance on how to achie ...

Storing Node_modules in a separate directory

All my node modules are located in the path C:/Users/user/AppData/Roaming/npm/node_modules. I am attempting to include these node modules with babel and babel-presets for my webpack scripts. Here is my webpack.config.js module.exports = { context: &a ...

"multer's single file upload functionality is not functioning properly, but the array upload

Currently, I am facing an issue while using react js to upload a single file. Interestingly, the multer.single() method seems to fail, whereas the multer.array() method works perfectly fine. What could be causing this problem? //Node.js const upload = mult ...

Placing a small image on top of multiple images using CSS

I am facing a CSS issue and I need help with positioning a small image (using position absolute) like a warranty badge on top of larger images. The challenge is to ensure that the badge is fixed at the bottom left corner of each image, despite variations ...

Missing callback pattern in NodeJS

When I spend hours writing NodeJS code, there's a common scenario that leaves me unsure of how to proceed. Take the following async function call (where we forget the necessary callback): function foo (callback) { // Perform a task and call callba ...

Scrolling using JavaScript's 'smooth scrolling' feature is currently disabled

Background of the Issue: I am in the process of creating a one-page website using Twitter Bootstrap 3 within an ASP.NET MVC project. The Challenge: My current challenge involves implementing 'smooth scrolling' functionality that scrolls to the ...

Experience the magic of a customized cursor that disappears with a simple mouse movement in your website,

I have been experimenting with designing a custom cursor for my website. After finding a design I liked, I made some adjustments to suit my needs. However, an issue I encountered is that when I scroll, the custom cursor also moves away from its original po ...

On page load, refresh the content of the div based on the selected radio button values

My goal is to automatically collect the values of checked radio buttons when the page loads, rather than waiting for a user interaction like clicking a radio button. Below is the JavaScript code I am using: $(function () { updateDivResult(); $(&a ...

Preserving CSS styling while loading an HTML page with InnerHTML

By using the following code snippet, I have successfully implemented a feature on my website that allows me to load an HTML page into a specific div container when clicking a link in the menu. However, I encountered an issue where the background color of ...