0

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); }) }

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I managed to maintain the reactivity but still doesn't work, it may has something to do maybe with what you mentioned about the direct DOM access, can you give me more details ? Thank you
One of the primary rules with VueJS is never directly modify the DOM. VueJS is build to do it. If you look at the Introduction in the Getting Started guide you will notice that there's no script at all to modify the DOM. As the variable count is in the data() method, VueJS will observe all changes you do to the variable. In the Template section, the variable count is binded using {{ }}. That refers directly to the count in the data() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.