Chart.js: `Uncaught TypeError: Cannot read property 'length' of null` (vuejs + chart.js)

Hello,

I am trying to use Chart.js with vuejs. Unfortunately, I’m already blocked from trying out the “beginners” example’…

Here’s my Vue Component:

<template>
  <canvas id="myChart" width="400" height="400"></canvas>
</template>

<script>
/*eslint-disable*/
import Chart from '../../node_modules/chart.js/src/Chart.js'
let ctx = document.getElementById("myChart")

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

export default {
  name: 'dashboard',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

And the error I get: Uncaught TypeError: Cannot read property 'length' of null

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 17 (4 by maintainers)

Most upvoted comments

Oh I see, <canvas>...</canvas> need to be declared before <script>...</script>

👍

@HornKild read my last/previous comment. The error was due to the element not being present in the HTML when Chart.js was trying to attach the chart on it.

do not put the chart in created …just put it in mounted . it just about the timing.

Just tried that, well I will see if upgrading (or getting rid of the lib altogether is possible). Thanks for all the help.

Actually I found the culprit, we have a legacy library: prototype (which I cannot simply trash) that is causing the issue. When I add that one to your fiddle, it breaks your implementation : https://fiddle.jshell.net/m8w0yz4b/5/ So I will probably skip on the jump of version… Or find another brilliant idea.

@AKFourSeven you can’t create a chart without a valid DOM reference (the canvas element must exist before constructing the chart), however the element doesn’t need to be attached to the DOM (see #4591). That’s a recent feature (v2.7), maybe you are not using the latest version.

Note: if you really need to import your scripts before your canvas element, you can still delay the chart creation until the DOM is fully loaded (jsfiddle):

<script>
window.addEventListener('load', function() {
  new Chart('chart', {
    type: 'line',
    data: // ...
  });
});
</script>
<canvas id="chart"></canvas>

Hit the same issue and yes the <canvas> tag must preceed the <script>, but there needs to be better error message. Nowhere in the documentation does it mention that it’s a strict requirement.