使用ChartJS更新图表 - VueJS

时间:2018-04-02 16:21:26

标签: javascript charts vue.js

所以我在尝试使用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)
    })
  }
}

非常感谢任何帮助! :)

1 个答案:

答案 0 :(得分:2)

我有类似的问题。我通过用nextTick

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