I'm trying to use axios to get data for my Chart but I couldn't know how to make it appear on the canvas, i can see the values on the console.log as below
Console.log, I'm not too sure what is happening, here's my code :
mounted(){
const ctx = document.getElementById('myChart');
let myData = [];
const myChart = new Chart(ctx,
{
type: 'line',
data: {
labels: [....],
datasets: [{
data: this.myData,
backgroundColor: [ ['blue']],
}] },
options: {.....}
});
myChart;
here's the methode:
created: function(){
this.getData();} ,
methods: {
getData : function(){
axios.get('http://localhost:3000/Chart/chartjs')
.then(resp => {this.myData = resp.data
console.log(resp.data); }) }
your problem is related to the reactivity fundamentals of VueJS. As you are declaring a local variable in the mounted method and trying to access the property myData on this without declaring it in the component, VueJS will not update the UI.
The way you presented your code, I'll assume that you are using VueJS3 with the Options API.
To have a reactive component, you need to declare a reactive state. This is usually done before the mounted() method.
export default {
data() {
return {
myData: []
}
},
mounted() {
...
Afterward, in your mounted and getData methods, instead of declaring myData, you need to use this.myData. VueJS will take care of the reactivity.
Also, I noticed that you are trying to access the DOM directly. This is not a usual or recommended in VueJS. You should use a bind to make sure your properties are updated correctly.