无法使Chart.js在Vue.js组件中运行

时间:2016-04-26 21:01:19

标签: chart.js vue.js

所以我试图在Vue.js组件中使用Chart.js显示一个漂亮的图表......不应该这么复杂但是我在那里撞墙。

这是我的组件代码(语法基于Vue.js webpack boilerplate

<template>

  <canvas v-el:canvas style="width: 100%; height: 200px"></canvas>

</template>

<script>
import Chart from 'chart.js'

export default {
  compiled: function () {

    // fetch canvas DOM element
    let canvas = this.$els.canvas

    // init chart.js
    let chart = new Chart(canvas, {
      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
            }
          }]
        }
      }
    })
    console.log(chart)

  }
}
</script>

我尽可能地简化了组件,并使用了doc示例中的数据(稍后将使用props绑定实际数据。)

所以我在控制台中不断收到此错误:

Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

我查了一下,似乎这与传递给Vue.js中使用的getComputedStyle的变量有关。

我最好的猜测this.$els.canvas不会返回正确的对象。但是如果我使用console.log在控制台中输出它似乎是正确的。

console.log(canvas)
// outputs <canvas style="width: 300px; height: 150px;"></canvas>
console.log(canvas.tagName)
// outputs CANVAS
console.log(canvas.style.height)
// outputs 200px

嗯,这实际上很奇怪,可能会有所帮助:您是否注意到我在模板中设置了画布style.height,但如果我console.log(canvas),我会看到height: 150px但是如果console.log(canvas.style.height) 1}}下面2行,我得到200px作为输出?!! WTF还在继续吗?Vue现在正在弄乱我的脑袋

链接到jsFiddle供您玩(在控制台中查看结果) https://jsfiddle.net/kartsims/g8s12yd2/3/#&togetherjs=CQrzT996AR

1 个答案:

答案 0 :(得分:3)

我想出了为什么会让你知道,以防万一有人碰巧在同一个位置:

我无法在Vue路由器显示的vue组件内工作 ...我认为这是因为我应该使用ready挂钩而不是compiled ...在compiled,DOM还没有完全准备就绪。