Javascript 打印预览时重画图形-不是函数(嵌套的Vue组件)

Javascript 打印预览时重画图形-不是函数(嵌套的Vue组件),javascript,vue.js,vuejs2,vue-component,Javascript,Vue.js,Vuejs2,Vue Component,我知道我没有正确地访问此函数,但我不确定如何调试此函数并确定正确的方法。感谢您的指导 PerformanceDonut.vue是Page.vue 性能螺母.vue: // ... methods: { drawGraph() { this.chart = new CanvasJS.Chart(this.chartName, this.chartOptions); this.chart.render(); console.log('Donu

我知道我没有正确地访问此函数,但我不确定如何调试此函数并确定正确的方法。感谢您的指导

PerformanceDonut.vue
Page.vue

性能螺母.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
        }
    });
}
控制台错误:

Uncaught TypeError: this.drawGraph is not a function

this
分配给名为
vm
的全局变量,然后在回调中访问它,因为回调中的执行上下文已更改:

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

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

                }
            });


您可以使用箭头功能将此
用作Vue组件的参考:

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

“在常规函数中,this关键字表示调用函数的对象,可以是窗口、文档、按钮或其他。对于箭头函数,this关键字始终表示定义箭头函数的对象。”谢谢!说明: