chart.js之Vue.js this.$el.getContext ('2d' ) 不是函数

tuyile006 阅读:188 2025-01-19 22:14:33 评论:0

我正在使用 Vue.js 版本 2 和 Charts.js 创建一个组件,我可以将数据传递到该组件,它会以一种很好的方式显示这些数据。这是我的代码:

<template> 
  <div class="container"> 
    <canvas width="900" height="400"></canvas> 
  </div> 
</template> 
 
<script> 
    export default { 
        props: ['customers','dates'], 
        mounted() { 
            console.log('Chart-Component mounted.'); 
            var context = this.$el.getContext('2d'); 
            console.log(context); 
            var myChart = new Chart(context, { 
                type: 'line', 
                data: { 
                    labels: this.dates, 
                    datasets: [{ 
                        label: '# of Votes', 
                        data: this.customers, 
                        backgroundColor: [ 
                            'rgba(255, 99, 132, 0.2)' 
                        ], 
                        borderColor: [ 
                            'rgba(255,99,132,1)' 
                        ], 
                        borderWidth: 3, 
                        cubicInterpolationMode: 'monotone', 
                        lineTension: 0 
                    }] 
                }, 
                options: { 
                    scales: { 
                        yAxes: [{ 
                            ticks: { 
                                beginAtZero:true 
                            } 
                        }] 
                    } 
                } 
            }); 
 
        } 
    } 
</script> 

如果我给 Canvas 一个 id 并通过以下方式获取上下文:

document.querySelector('#graph').getContext('2d'); 

它工作得很好,但我只能使用我的组件一次,这显然不是我想要的。所以我试图通过以下方式获取上下文:

this.$el.getContext('2d'); 

但随后出现以下错误:

[Vue warn]: Error in mounted hook: "TypeError: this.$el.getContext is not a function"

我用谷歌搜索并查看了文档,但老实说,我对 vue 真的很陌生,我不确定我还能搜索什么......

因此,如果有人可以帮助我或可以告诉我下一步应该检查什么,我们将不胜感激!谢谢

请您参考如下方法:

this.$el 在这种情况下是对 div#container 的引用。你想要做的是使用 ref .

ref is used to register a reference to an element or a child component. The reference will be registered under the parent component’s $refs object

<div class="container"> 
  <canvas ref="canvas" width="900" height="400"></canvas> 
</div> 

然后

this.$refs.canvas.getContext('2d')  


标签:VUE
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号