gpt4 book ai didi

javascript - 使用 ChartJS 更新图表 - VueJS

转载 作者:行者123 更新时间:2023-12-01 02:13:19 24 4
gpt4 key购买 nike

所以我在尝试使用 VueJS 和 ChartJS 更新图表时遇到了一些问题。我当前正在运行 ajax 请求(使用 axios)并尝试根据返回的数据绘制图表。

问题是在尝试绘制图表时出现以下错误:TypeError: Cannot read property 'getContext' of undefined at eval (App.vue?26cd:520)。我真的不知道为什么会发生这种情况,我读过其他一些帖子,但似乎仍然无法让它工作。这是我正在使用的代码:

<template>
<button @click="myFunction()">Click Me</button>
<canvas ref="myChart"></canvas>
</template>
-----------------------------------------------------------

methods: {
myFunction () {
var self = this

axios.post('http://localhost/link/to/file.php', {
// Post params here
}).then(response => {
var ctxChart = self.$refs.myChart.getContext('2d')

var myChart = new Chart(ctxChart, {
type: 'pie',
data: {
labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4'],
datasets: [{
label: 'Label here',
data: [response.data['data1'], response.data['data2'], response.data['data3'], response.data['data4']],
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)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
],
borderWidth: 1
}]
},
options: {
}
})

}).catch(e => {
console.log(e)
})
}
}

非常感谢任何帮助! :)

最佳答案

我也遇到过类似的问题。我通过用 nextTick

包装所有内容解决了这个问题
self.$nextTick(() => {
var ctxChart = self.$refs.myChart.getContext('2d')
...
});

关于javascript - 使用 ChartJS 更新图表 - VueJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49614851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com