[Chartjs]-Vue.js vue-chartjs chart not updating when chartData replaced, updated etc

4👍

✅

Billy Jean final note worked for me PIECHART.JS:

import {
 Pie,
 mixins
} from 'vue-chartjs'
const {
reactiveProp
} = mixins

export default Pie.extend({
   mixins: [reactiveProp],
   props: ['options'],
watch: {
'options': {
  handler(newOption, oldOption) {
    this._chart.destroy()
    this.renderChart(this.chartData, this.options)
  },
  deep: true
}
    },
  mounted() {      
    this.renderChart(this.chartData, {responsive: true, maintainAspectRadio: 
    false})
   }
})

This is in my view.vue File:

 let datasets = []
  let colorlist = [ '#4e5fa4', '#5e5fa4', '#6e5fa4',
  '#7e5fa4', '#8e5fa4', '#a08be4', '#b08bd4']
        datasets.push({
          label: this.data_by_city_label,
          data: this.data_by_city_data,
          fill: false,
          backgroundColor: colorlist,
          pointBorderWidth: 1,
          borderWidth: 1,
          pointRadius: 0
        })
  this.CityDatac = Object.assign({}, this.datasets, {labels: this.data_by_city_label, datasets: datasets})

With this i can send my data to the PIECHART js and generated in my view.vue
as so:

   <pie-chart-city :chartData="CityDatac" :width="300" :height="250"></pie-chart-city>

Hope that helps anyone in VUE.js -> Vue-chartjs.js

8👍

One way that works is to add a watcher to the chart,

props: ['chartData', 'options'],
mounted () {
  this.renderChart(this.chartData, this.options)
},
watch: {
  'chartData' (to, from) {
    this.renderChart(this.chartData, this.options)
  }
},

See example CodePen


Edit – watcher not working

The difference between your code and the working CodePen is that CodePen mutates the variable passed into the chart, therefore it’s watcher reacts.
Your code mutates the .datasets property of the variable – there’s a known issue with this ref: Mixins don’t seem to trigger a refresh of the chart #44.

Try replacing

this.datacollection.datasets = [];
this.datacollection.labels = [];

with this (both places)

this.datacollection = { datasets: [], labels: [] };

0👍

The code posted by Alexis Poo points me in the right direction.

In my case, I need to modify the watch object a little bit.

When trying to destroy the chart by calling this._chart.destroy() when option changed, I received an error message: cannot read property 'destroy' of undefined.

To fix the issue, I have to do this.$data._chart.destroy() instead.

Hope it helps.

Leave a comment