2017-06-16 916 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') 
相關問題