【发布时间】:2021-04-08 19:12:21
【问题描述】:
您好,我正在尝试通过调用 API 来使用 chartjs 显示不同的图表。下面的代码显示了我如何格式化chart.vue
Chart.vue:
<template>
<div class="chart-container" style="position: relative; height: 40vh; width:100%;">
<slot name="test1"></slot>
<slot name="test2"></slot>
</div>
</template>
<script>
export default {
name: 'charts',
data () {
return {
date: [],
challenge: [],
data: []
}
},
mounted () {
this.check(8, 'chart_8')
this.check(7, 'chart_7')
},
methods: {
check (id, name) {
this.$http.get(`/api_chart/${ id }/full`)
.then((response) => {
this.date = response.data.date
this.challenge = response.data.challenge
this.data = this.date.map((date, index) => ({
x: new Date(date * 1000),
y: this.challenge[index]
}))
const ctx = document.getElementById([name]).getContext('2d')
let myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: 'Challenge',
data: this.data,
borderColor: ' #EA5455',
}
]
},
options: {
lineTension: 0,
maintainAspectRatio: false,
scales: {
yAxes: [
{
scaleLabel: {
display: false
},
ticks: {
beginAtZero: true,
callback (value) {
return `${value}%`
}
}
}
],
xAxes: [
{
type: 'time',
time: {
unit: 'month'
},
scaleLabel: {
display: true,
}
}
]
}
}
})
})
}
}
}
</script>
App.vue:
<template>
<div class="In order to display chart1">
<chart-display> <canvas slot="test1" id="chart_7" ></canvas> </chart-display>
</div>
<div class="In order to display chart1">
<chart-display> <canvas slot="test2" id="chart_8" ></canvas> </chart-display>
</div>
</template>
<script>
import chart-display from './Chart.vue'
export default {
component: {chart-display}
}
</script>
如您所见,我已经共享了我的 Chart.vue 和 App.vue,我可以在浏览器中看到我的图表,但是每当我运行代码或刷新页面时,图表都会闪烁并停止。然后在我的控制台中出现以下错误:
请有人帮我解决这个问题,并请告诉我是否应该对我的代码进行任何更改来解决它。请把修改码发给我。
【问题讨论】:
-
你考虑过使用 vue-chartjs 吗?
-
是的,最初我尝试使用 vue-chartjs,但图表没有显示在浏览器中。所以我决定我将使用 chartjs 显示图表
-
我在工作中使用 vue-chartjs 没有任何问题。错误日志说,
ctx为空,首先检查 canvas 元素是否真的存在。 -
能否请您在代码沙箱中分享您的 vue-chartjs,我将通过它,并尝试在我的项目中实现相同的东西。
-
我应该在数据中定义画布吗?请告诉我应该在我的代码中进行哪些更改才能完成结果