我正在尝试从Vue.js和Vuetify应用程序上的chart.js库中加载图表,但是显示以下错误:
无法创建图表:无法从给定项目获取上下文
然后,当我尝试添加.getContext(“ 2d)函数时,它无法解决错误。挂载的方法似乎运行良好,因为我运行了其他功能而没有任何问题,所有内容似乎都已导入正确。我已经尝试过使用JQUERY,但仍然存在相同的错误。
以下是我的文件供参考: app.vue:
来自模板的画布:
<canvas id="charting" width="600px" height="600px">
</canvas>
app.vue JS:
<script>
import Chart from '../../../../node_modules/chart.js'
import coinCharts from './scripts/charts/randomcoin.js'
export default {
data() {
return {
coinCharts: coinCharts
}
},
methods: {
createChart(id, chartData) {
const ctx = document.getElementById(id).getContext("2d");
const chartRender = new Chart(ctx, {
type:chartData.type,
data:chartData.data,
options: chartData.options
})}
},
mounted() {
this.createChart("charting", this.coinCharts);
}
}
带有图表数据的导入脚本:
export const coinCharts = new Chart({
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
options: {
responsive:true,
lineTension:1
}
})
export default coinCharts;
编译时,显示以下错误:
Module Warning (from ./node_modules/eslint-loader/index.js):
error: 'chartRender' is assigned a value but never used (no-unused-vars)
at src\components\views\coins\AlphaCoin.vue:50:11:
createChart(id, chartData) {
const ctx = document.getElementById(id).getContext("2d");
const chartRender = new Chart(ctx, {
type:chartData.type,
data:chartData.data,
options: chartData.options
答案 0 :(得分:0)
您似乎两次致电new Chart()
。一次出现在图表数据randomcoin.js
上,也出现在createChart(id, chartData)
方法上。尝试将图表数据更改为这样的对象:
export const coinCharts = {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
options: {
responsive:true,
lineTension:1
}
}
export default coinCharts;
这应该可以解决您的问题。