Redraw Graph on Print Preview - Is Not a Function (Nested Vue Component)

Viewed 150

I know I'm not accessing this function correct by the error, but I'm not sure how to debug this and determine the correct approach. Guidance is appreciated.

PerformanceDonut.vue is a component in Page.vue

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 executes here

    // Redraw graph on print preview
    window.matchMedia('print').addListener(function(mql) {
        if (mql.matches) {
            this.drawGraph();
            // Error here
        }
    });
}

Console Error:

Uncaught TypeError: this.drawGraph is not a function
2 Answers

Assign this to a global variable called vm and then access it in the callback since the execution context is changed in the callback:

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

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

                }
            });

You can use an arrow function in order to work this as reference of Vue component:

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