0

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! :)

4
  • Put a breakpoint and make sure that myChart is a defined $ref. Commented Apr 2, 2018 at 16:26
  • If this is all the code, then problematic line is var ctxChart = self.$refs.myChart.getContext('2d'). When do you call myFunction? Make sure to call if after mounted Commented Apr 2, 2018 at 16:27
  • @FrEaKmAn I call it when the button is clicked @click="myFunction()". Commented Apr 2, 2018 at 16:28
  • @zero298 Hmm whenever I do a console.log(self.$refs) I can see my chart reference there. But when I do a console.log(self.$refs.myChart) I get Undefined. Commented Apr 2, 2018 at 16:30

1 Answer 1

3

I had similar problem. I solved it by wrapping everything with nextTick

self.$nextTick(() => {
    var ctxChart = self.$refs.myChart.getContext('2d')
    ...
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It worked perfectly. Didn't know about nextTick().

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.