[Chartjs]-Vue.js chart not working?

2👍

You are accessing the canvas element in the created() hook, which is called before your template is attached to the DOM.

To solve your problem you need to put your code into the mounted() hook of your component. But still, it is not guaranteed that the template is in document. So you have to use $vm.nextTick() to ensure the DOM is ready. (source).

Also, I recommend using vue’s Child component refs, which is more vue-like than document.getElementById() (it works too).

Vue.component('message-graph', {

  template: '<canvas ref="chart" width="400" height="400"></canvas>',

  mounted() {
    this.$nextTick(() => {

      let myChart = new Chart(this.$refs.chart, {
        type: 'bar',
        data: {
          labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
          datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
              'rgba(255, 99, 132, 0.2)',
              'rgba(54, 162, 235, 0.2)',
              'rgba(255, 206, 86, 0.2)',
              'rgba(75, 192, 192, 0.2)',
              'rgba(153, 102, 255, 0.2)',
              'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
              'rgba(255,99,132,1)',
              'rgba(54, 162, 235, 1)',
              'rgba(255, 206, 86, 1)',
              'rgba(75, 192, 192, 1)',
              'rgba(153, 102, 255, 1)',
              'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        }
      })

    })
  }

})

let vue = new Vue({
  el: '#app',
  template: '<div class="myApp"><message-graph></message-graph></div>'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>

<div id="app"></div>

Leave a comment