所以我试图在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
答案 0 :(得分:3)
我想出了为什么会让你知道,以防万一有人碰巧在同一个位置:
我无法在Vue路由器显示的vue组件内工作 ...我认为这是因为我应该使用ready
挂钩而不是compiled
...在compiled
,DOM还没有完全准备就绪。