Vue.js这个。$ el.getContext('2d')不是函数

时间:2017-06-16 15:57:08

标签: 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>

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

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

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

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

然后我收到以下错误:

  

[Vue警告]:挂钩错误:“TypeError:this。$ el.getContext不是函数”

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

所以,如果有人可以帮助我,或者可以告诉我接下来要检查的内容,我们将非常感谢!谢谢

1 个答案:

答案 0 :(得分:4)

在这种情况下,

context是对this.$el的引用。你想要做的是使用ref

  

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

div#container

然后

<div class="container">
  <canvas ref="canvas" width="900" height="400"></canvas>
</div>
相关问题