axJET后,chartJS饼图没有更新

时间:2018-05-18 21:42:52

标签: vue.js chart.js

在我的Vue应用程序中,我正在加载页面,它从我的Flask后端获取一些数据。我绘制了一堆元素,我还根据从后端返回的3个值的数组绘制饼图。当我收到回复时,我更新了this.pie_data,我认为这会在我的模板中更新,以反映饼图。它渲染了this.nvrs中设置的元素,因此不确定它为什么不能用于我的饼图。

感谢帮助。

模板

<div class="box">
  <p class="title">System Overview</p>
  <chart :type="'pie'": data=chartData></chart>
</div>

脚本

import axios from 'axios'
import Chart from 'vue-bulma-chartjs'

export default {
  name: 'NVR_Overview',
  components: {
    Chart,
  },
  data: () => ({
    nvrs: [],
    // Health, Down, Warn
    pie_data: [],
  }),
  methods: {
    goToNVR (nvrId)
    {
      let wpsId = this.$route.params['wpsId']

      let path = '/wps/' + wpsId + '/nvr/' + nvrId
      this.$router.push(path)
    },
  },
  created ()
  {
    axios
      .get('http://localhost:5000/wps/' + this.$route.params['wpsId'])
      .then(response =>
      {
        this.nvrs = response.data['nvr_list']
        this.pie_data = response.data['pie_data']
        console.log(this.pie_data)
      })
      .catch(e =>
      {
        console.log(e)
      })
  },
  computed: {
    chartData ()
    {
      return {
        labels: ['Healthy', 'Down', 'Warning'],
        datasets: [
          {
            data: this.pie_data,
            backgroundColor: ['#41B482', '#ff4853', '#FFCE56'],
          },
        ],
      }
    },
  },
}

1 个答案:

答案 0 :(得分:1)

解决方案1: 在进行更改时复制旧图表数据引用(旧数据具有Observer,因此不要使用完成的新对象),而不是使用计算值,请使用watch:

<template>
  <div class="box">
    <p class="title">System Overview</p>
    <chart :type="'pie'" :data="chartData"></chart>
  </div>
</template>

<script>
import axios from 'axios'
import Chart from 'vue-bulma-chartjs'

export default {
  name: 'NVR_Overview',
  components: {
    Chart,
  },
  data: () => ({
    nvrs: [],
    // Health, Down, Warn
    pie_data: [],
    chartData: {
      labels: ['Healthy', 'Down', 'Warning'],
      datasets: [
        {
          data: [],
          backgroundColor: ['#41B482', '#ff4853', '#FFCE56'],
        },
      ]
    }
  }),
  methods: {
    goToNVR (nvrId)
    {
      let wpsId = this.$route.params['wpsId']

      let path = '/wps/' + wpsId + '/nvr/' + nvrId
      this.$router.push(path)
    },
  },
  created ()
  {
    axios
      .get('http://localhost:5000/wps/' + this.$route.params['wpsId'])
      .then(response =>
      {
        this.nvrs = response.data['nvr_list']
        this.pie_data = response.data['pie_data']
        console.log(this.pie_data)
      })
      .catch(e =>
      {
        console.log(e)
      })
  },
  watch: {
    pie_data (newData) {
      const data = this.chartData
      data.datasets[0].data = newData
      this.chartData = {...data}
    }
  },
}
</script>

您可以在vue-bulma-chartjs存储库https://github.com/vue-bulma/chartjs/pull/24

上查看此问题

解决方案2 : 添加参考图表

<chart ref="chart" :type="'pie'" :data="data"</chart>

然后在分配数据后在脚本中:

  this.$nextTick(() => {
    this.$refs.chart.resetChart();
  })