Reputation: 1027
so I'm having some problems when trying to update a chart using VueJS and ChartJS. I'm currently running a ajax request (using axios) and trying to draw a chart from the data returned.
The problem is when trying to draw the chart I get the following error: TypeError: Cannot read property 'getContext' of undefined at eval (App.vue?26cd:520)
. I don't really know why this is happening, I've read some other posts but still can't seem to get it working. This is the code I'm using:
<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)
})
}
}
Any help is greatly appreciated! :)
Upvotes: 0
Views: 1104
Reputation: 1845
I had similar problem. I solved it by wrapping everything with nextTick
self.$nextTick(() => {
var ctxChart = self.$refs.myChart.getContext('2d')
...
});
Upvotes: 3