2017-06-16 914 views
2

我在与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 warn]: Error in mounted hook: "TypeError: this.$el.getContext is not a function"

我用Google搜索,并检查了文件,但说实话我真的很新的Vue和我不确定我可以搜索什么...

所以,如果任何人都可以帮助我,或可以告诉我我应该检查下一个它将不胜感激!谢谢

+0

您使用weex,图表和weex-gcanvas插件?你有任何示例代码来分享如何使用它?官员不再工作了。 – Nora

回答

3

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') 
相关问题