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

N. *_*Kue 3 chart.js vuejs2

我正在使用 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>
Run Code Online (Sandbox Code Playgroud)

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

document.querySelector('#graph').getContext('2d');
Run Code Online (Sandbox Code Playgroud)

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

this.$el.getContext('2d');
Run Code Online (Sandbox Code Playgroud)

但后来我收到以下错误:

[Vue 警告]:挂载钩子错误:“TypeError: this.$el.getContext is not a function”

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

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

Ber*_*ert 5

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

ref 用于注册对元素或子组件的引用。该引用将注册在父组件的 $refs 对象下

<div class="container">
  <canvas ref="canvas" width="900" height="400"></canvas>
</div>
Run Code Online (Sandbox Code Playgroud)

进而

this.$refs.canvas.getContext('2d') 
Run Code Online (Sandbox Code Playgroud)