LoginSignup
13
9

More than 5 years have passed since last update.

Vue.jsでChart.js使ったらはまった(グラフが出ない):解決済み

Last updated at Posted at 2018-03-21

概要

突貫コーディングをしていたところChart.jsのグラフが描画されないことがありました。
僕がVue.jsの仕様をちゃんと把握していないことが原因で反省文代わりに書きます。
同じことではまる人の参考になればと思います。
詳しいことは追々学習します、投げっぱなし投稿スミマセンスミマセン!!

乱暴な結論

  • おとなしくvue-chartjs使え
  • DOMの更新タイミングを考えろ

詳細

諸事情によりVue.js使っているのにvue-xxxx系のモジュールを使っていませんでした。
下記「グラフが出なかった時のコード」でブラウザのDeveloper Toolsを見ると「Canvasが見つからねーよ(意訳)」とかで怒られた…と思う(うろ覚え
正しくエレメントが取得できることとDOMの描画タイミングがポイントっぽい。

構成

  • Vue.js:2.x系
  • Chart.js:2.7.1

グラフが出なかった時のコード

HTML

index.vue
<template lang="pug">
  div#app
    canvas#myChart
</template>

JavaScript

※読み込みはmain.jsで行っている前提です。

index.vue
<script>
var ctx = document.getElementById("myChart").getContext('2d');
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],
            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
                }
            }]
        }
    }
});
</script>

グラフが出るコード

HTML

変更なし

JavaScript

index.vue
export default {
  mounted () {
    this.$nextTick(() => {
      const ctx = this.$el.querySelector('#canvas').getContext('2d')
      this.chart = new Chart(ctx, {
        type: 'bar',
        data: {
          //いい感じに
        },
        oprions: {
          //いい感じに
        }
      })
    })
  }
}

参考ページ

13
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9